I Just Can’t Stop Logging You

I like my simple applications as small as possible. If needed I implement a simple textfile-writer for logging. For bigger applications there’s log4net.

These are the steps

  1. Add Log4net with nuget to your project
  2. Add to assembly.cs:
    [assembly: log4net.Config.XmlConfigurator(Watch=true)]
  3. We will add the lognet section in an external file, but the Web.config (or App.Config) needs some small modifications:
    <configuration>
    <configSections>
    <section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler, log4net”/>
    […]
    </configSections>
    […]
    <log4net configSource=”App_Config\Log4net.config” />
    […]
    <startup>
    <supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.5″ />
    </startup>
    </configuration>
  4. Add a config file “Log4net.config” in App_Config:
    <?xml version=”1.0″ encoding=”utf-8″ ?>
    <log4net>
    </log4net>
  5. Add a root node to the log4net-node. You can setup multiple logs, the root contains the basic settings:
    <root>
    <level value=”INFO” />
    </root>

There are different log-levels:
0 NONE
1 FATAL
2 ERROR
3 WARN
4 INFO
5 DEBUG
6 ALL
If you select INFO, then INFO events but also WARN, ERROR and FATAL will be logged.

6) Now we have to add an appender – the log definition:

<appender name=”MyAppLog” type=”log4net.Appender.FileAppender”>
<file value=”App_Data/Logs/application.log” />

<appendToFile value=”true” />
<lockingModel type=”log4net.Appender.FileAppender+MinimalLock” />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%date %level %logger – %message%newline” />
</layout>
<encoding value=”utf-8″ />
</appender>

7) To use this, you must add a reference to the root node
<root>
<level value=”INFO” />
<appender-ref ref=”MyAppLog” />
</root>
8) In the examples you can add a log- field on top of every class. I choose to add a shared LogUtil:

public static class LogUtil
 {
 private static bool isConfigured;

private static readonly Object lockObj = new Object();
 private static volatile ILog appLog;


 /// <summary>
 /// Gets the website logger.
 /// </summary>
 /// <value>
 /// The website.
 /// </value>
 public static ILog AppLog
 {
 get
 {
 if (appLog != null)
 {
 return appLog;
 }

lock (lockObj)
 {
 if (appLog != null)
 {
 return appLog;
 }
 if (!isConfigured)
 {
 isConfigured = true;
 XmlConfigurator.Configure();
 }

appLog = LogManager.GetLogger("MyAppLog");
 }
 return appLog;
 }
 }
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s