code-u-like

C#, .Net, Sql Server, Salesforce, Dynamics CRM etc,
Charity and Not-for-Profit sector

Friday, May 28, 2010

Quick Elmah setup

Elmah is great. Its an error logging utility that you can drop into a .net app without changing any code. You just drop the DLL in the bin folder, and make a few web.config changes. OK, these days you can achieve the same thing with ASP.NET Health Monitoring, but Elmah is nice and easy, and the web pages it provides to inspect the error log are cool.

There are loads of different ways of configuring Elmah (you can get it email errors to you, for example) and the 'demo' that comes with the download shows most of the options. But in most cases you'll want bog-standard logging to a local db, so these notes cover doing that.

1. Download Elmah

Download from here.

2. Drop DLLs into Bin folder

Unpack the download and look for the appropriate bin folder, usually you'll want the Release version of .NET 2.0 or .NET 3.5. From that bin folder, copy the Elmah.dll and the SQLLite.dll to the Bin folder for your web app.

E.g, these two files:
ELMAH-1.1-bin\bin\net-2.0\Release\Elmah.dll
ELMAH-1.1-bin\bin\net-2.0\Release\System.Data.SQLite.dll


3. Add things to your web.config

Copy the bold sections below into the right places in your web.config:

<?xml version="1.0"?>
<configuration>
  <configSections>
    ... 
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
    </sectionGroup>  </configSections>
  ...
  <elmah>
    <errorLog type="Elmah.SQLiteErrorLog, Elmah" connectionStringName="ELMAH.SQLite" />
    <security allowRemoteAccess="0" />
  </elmah>
  <connectionStrings>
    <add name="ELMAH.SQLite" connectionString="Data Source=|DataDirectory|errors.s3db"/>
    ...
  </connectionStrings>
  <system.web>
    ...
    <httpHandlers>
      ... 
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
    </httpHandlers>
    <httpModules>
      ...
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
    </httpModules>
    ...
  </system.web>
  <system.webServer>
    <modules>
      ..
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
    </modules>
    <handlers>
      ...
      <add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD"
        type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
    </handlers>
  </system.webServer>
  ...
</configuration>
4. Off it goes!

Thats it, really. Elmah will now catch and log all unhandled Exceptions.

If you now run your web app, and on the web server browse to:
http://localhost/YourAppName/Elmah.axd

... you will see the Elmah error log.

Note that the config settings given above ensure that viewing the error log is only accessible from the web server itself.

If you want to manually log errors, for example Exceptions that you have caught in a try..catch block, then you can use code like this:
catch (Exception e)
{
  Elmah.ErrorSignal.FromCurrentContext().Raise(e);
  ...
}
(If you are using an ASP.NET Web Application Project, you'll also need to add a reference to Elmah.dll to be able to access Elmah in code)

Labels:

Quick Log4net setup

Log4net has lots of options and different ways it could be configured - these are notes written to myself so that I can get it working quickly.

1. Download log4net

Download from here.

2. Drop DLL in Bin folder

In the download package, there are various DLLs, usually you'll want the .net 2.0 release version at:
incubating-log4net-1.2.10\log4net-1.2.10\bin\net\2.0\release
If you have an ASP.NET Web Application Project (as opposed to an ASP.NET Web Site) then you'll also need to add a reference to the DLL.

3. Add a Configurator line in the Global.asax

There are various ways of telling Log4net to pick up its config. We're going to use the Xml Configurator that pulls config from a separate config file. Add this line of code to Application_Start in the Global.asax:
void Application_Start(object sender, EventArgs e) 
{
    log4net.Config.XmlConfigurator.Configure();
}
4. Add an AppSetting to the web.config

The XmlConfigurator.Configure() call above, tells Log4net to look for a certain key in appSettings. The key gives the name of the config file. So we add the correct appSetting entry to web.config, like this:
<appSettings>
    ...
    <add key="log4net.Config" value="logging.config" />
    ...
5. Add a logging.config file

In the root folder (same folder as web.config), add the following logging.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="App_Data/Log.txt" />
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d thread%-2t %-5p src:%-25c - %m%n" />
      </layout>
    </appender>

    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>
This has basic options for logging to a text file in the App_Data folder (make sure you have an App_Data folder). Its set to log everything, because during development thats what you'll want to do, right?

6. Add logging statements

One good pattern for this is to have a static logger for each page:
public partial class MyWebPage : System.Web.UI.Page
{
    private static readonly ILog logger = LogManager.GetLogger(typeof(MyWebPage));
    
    protected void Page_Load(object sender, EventArgs e)
    {
        logger.Debug("page load");
    }
    ...


So ... thats one way of doing it. There are, of course, millions of other ways.

Labels: