During a current project in work (one of many) I required a logging system for recording info and errors during operation so that I can easily and quickly debug the application when it is in service. As I was already aware of the extremely successful Log4j I decided to give its .Net counterpart a chance and have been very happy with it.
However, it did take me some amount of playing to get it working – despite the very useful tutorials that are available I was still unable to get it going the way I wanted to, that is to have some very simply code that can be easily ported to another project with minimal fuss (i.e. a config file that can be used with only minor additional commands within the code). I eventually worked out that the problem I was having was not my code, but that none of the tutorials noted that the config file had to be manually (or scripted) moved to the executable location (yes, obvious when you think about it!).
Anyway, see below the contents of my team wiki, hopefully it will come in handy for someone else.
To use Log4Net for logging in a C# application follow these steps:
- Add the following at the top of your AssemblyInfo.cs file (under Properties):
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
- Add the following as a Post-build event in your Project Properties:
copy $(ProjectDir)Log4Net.config $(ProjectDir)$(OutDir)
- Create a Log4Net.config file in your project root as per your requirements, such as:
<log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date{ABSOLUTE} [%thread] %level %logger - %message%newline" /> </layout> </appender> <root> <level value="INFO" /> <appender-ref ref="ConsoleAppender" /> </root> </log4net>
- Add the following declaration at the top of the class in which you require logging to take place:
private static readonly ILog log = log4net.LogManager.GetLogger(typeof(Program));
- Enter output messages where necessary i.e. log.Info(“message”), log.Debug(“message”) etc.
It is recommended that you use at the minimum a ConsoleAppender and FileAppender class. For more information see: http://logging.apache.org/
One reply on “How to use Log4Net in C#”
[…] debug your app during development but especially during production. I have previously demonstrated how to use Log4Net in C# which enables you to log output to your console for the former and to a file for the latter, but […]