Using log4net with Tridion Console apps

April 26th, 2013 | Posted by Robert Curlette in .NET

In my previous article I described how to use a Console application to check-in items using the Core Service. In this article I will describe how to setup and use the log4net framework to output content to the Console window and also to a log file.

1. Get the log4net DLLs using NuGet. Right-click on the project name and select ‘Manage Nuget Packages’. If you do not have this option then download NuGet and then try again.

2. Update the app.config file with the log4net configuration. NuGet packages can modify our config files, but unfortunately the log4net NuGet package does not.

This configuration does the following:
– Specifies a Console Logger to automatically write all messages to the console
– Uses a Date rolling file appender

<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level: %message%newline" />
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="CheckinItems.log"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="7" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5level %date{yyyy-MM-dd HH:mm:ss} - %m%n"/>
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="Console" />
</root>
</log4net>
</configuration>

3. Add this code to your Main method to startup log4net

XmlConfigurator.Configure();

4. Instantiate an instance of a logger

private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

5. Write a log message

log.Info("log something");

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *