The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

Log4Net is an extremely useful tool that allows developers to output statements to a variety of destinations. The home page for log4net can be here and it has links to the binaries.
 
A really quick “get up and go” example is included here to get the ball rolling.
 
The following additions need to go into your application config file:
 
1) Add a new configuration section. If you don’t already have a <configSections> node in your config file, remember that it must be the first entry after the <configuration> node.
 
    <configSections>
        <sectionname="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
 
2) The next section can be put into the configuration file and should be at the same level as the <configSections> node (i.e. The parent node should be <configuration>)
 
    <log4net>
        <appendername="RollingFile"type="log4net.Appender.RollingFileAppender">
            <filevalue="C:\MyLog.log"/>
            <appendToFilevalue="true"/>
            <rollingStylevalue="Size"/>
            <maxSizeRollBackupsvalue="10"/>
            <maximumFileSizevalue="1000KB"/>
            <immediateFlushvalue="true"/>
            <staticLogFileNamevalue="true"/>
            <layouttype="log4net.Layout.PatternLayout">
                <conversionPatternvalue="%date [%thread] %-5level %logger - %message%newline"/>
            </layout>
        </appender>
        <root>
            <levelvalue="DEBUG"/>
            <appender-refref="RollingFile"/>
        </root>
    </log4net>
</configuration>
 
Take note of the <appender> section: You can add many appenders to the logging, each with different destination outputs, or the same with different layouts. The appenders you decide to use go into the <root> section.
You can also set the starting log level, as seen in <levelvalue="DEBUG"/>. The levels in log4net are in the order DEBUG -> INFO -> WARNING -> ERROR -> CRITICAL, and the level specified is the level that logging will start at.
 
3) Add this to your assembly info file to enable the logging.
 
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
 
4) Use log4net in your code:
 
publicstaticreadonlyILog _log = LogManager.GetLogger("MyLogger");
 
_log.Debug("Here is my log output");
 
I find that adding the declaration line at the top of a class/base-class makes for easy access to the logger throughout the code. You may also notice that the GetLogger method takes a string or type as a parameter. I’ll explain that in more detail in the next articles.
 
posted on Friday, August 03, 2007 7:53 AM
Comments have been closed on this topic.