Using log4Net in a Windows Console app
December 27, 2007 in C# by Michael Chrisman 0 Comments
One of the most import parts to any application is logging (the reasons why I think this will have to wait for another entry). I have seen a couple of home-grown logging classes that were somewhat useful, but very restrictive. Recent I would shown how Log4Net works. Now Log4Net (and the Java version Log4J) are both open source tools (free). The demo was on how to integrate it into an ASP.Net application (see Chris Brandsma's blog entry on it). His demo and blog works well for ASP.Net applications, but I do a lot of console application (interfaces between two applications). The needs of a console app are different. These often run unattended and although having Warning and Info entries in a log file is good, you only want Error entries in the Server Event log. Well, after some trail and error and searching, I figured out to 1) get Log4Net configured for a console app and 2) get it to write all entries to a log file and console and write just errors to the Event log on the server.
OK, let's get started. The first step is adding a bunch of stuff to the App.Config file. There are two sections you will need to add. The first is in the configSections section (If you don't have one in your App.Config, then just it.)
1: <configSections>2: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />3: configSections>
Next you need to add a whole new section called log4net. This is where you tell log4net where to write what information for logging. Log4Net uses something called Appenders and there are a lot of them. This example creates a log file (called MyApp.log) which everything will get written to. It also writes everything to the console. It also creates the appender for the Server event log, but only writes Errors to it. Add this section so at it is not part of any other section. Here is the code
1: <log4net>2: <appender name="Console" type="log4net.Appender.ConsoleAppender">3: <layout type="log4net.Layout.PatternLayout">4: <conversionPattern value="%date [%level] %thread %logger - %message%newline" />5: layout>6: appender>7: <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">8: <param name="file" value="MyApp.log" />9: <param name="appendToFile" value="true" />10: <param name="maximumFileSize" value="100KB" />11: <param name="maxSizeRollBackups" value="2" />12: <layout type="log4net.Layout.PatternLayout">13: <conversionPattern value="%date [%level] %thread %logger - %message%newline" />14: layout>15: appender>16: <appender name="EventLog" type="log4net.Appender.EventLogAppender" >17: <threshold value="ERROR"/>18: <layout type="log4net.Layout.PatternLayout">19: <conversionPattern value="MyApp.exe has thrown an error and was unable to complete its task. This is the error message (please see the log file for more details):%newline%newline %message" />20: layout>21: appender>22: <root>23: <level value="ALL" />24: <appender-ref ref="Console" />25: <appender-ref ref="RollingFile" />26: <appender-ref ref="EventLog"/>27: root>28: log4net>
Lines 2-7 set up the Console appender. Lines 9-18 setup a log file. Line 10 denotes the file name and since there is not path information, it will be in the current folder. Lines 20-25 setup the Windows Event log appender. Line 21 is what tells Log4Net to only log Errors to this appender. Lines 27-32 turn on each appender. Line 28 denotes that everything will be logged. If you change this to Info then only Info, Warn and Errors will be logged. If you set it to Warn, then only warnings and errors will be logged. OK that's it for the App.Config. Let look at the code now.
The first thing you have to do is add a reference to the Log4Net.dll (you will probably have to browse for it where ever you setup the log4net files).
Next you need to add a using statement for the Log4Net. There are two of them.
1: using log4net;2: using log4net.Config;
OK, now you will want to create an object level variable (so you can access it from any method without having to pass it around everywhere).
1: class MyClass2: {3: private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(typeof (MyClass));4: …
Now that we have it setup, we have to initialize it. This is where things got fun figuring out. If you just call .Configure(), then it initialized to the console and ignores what you have in the App.Config. You have to call the XmlConfigurator.Configure() in order to force it to read your App.Config.
1: static void Main(string[] args)2: {3: log4net.Config.XmlConfigurator.Configure();4: …
OK, that's it. Now you just put in all the logging events you like. The main ones you will use are Error, Warn, Info and Debug.
1: _logger.Debug("This is Debug text");2: _logger.Info("This is Info text");3: _logger.Warn("This is Warn text");4: _logger.Error("This is Error text");
The cool part is that you can leave in all your debug lines and just change the Root->Level value in the App.Config to have the system ignore these. Well that is how to setup log4Net in your console application.