RSS
Giga Web Solution - Gaetano Santonastaso

DateTime in Log4net file name

Creating a log4net file with date is pretty straightforward but when the file name contains the time as well you may encounter some issue.

I was recently working on a project where I had to create a log file with Date and Time in the name. My first attempt has been to use the following settings


<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="C:\temp\PasswordMigrator\GaetanoLog_" />
            <appendToFile value="true" />
            <datePattern value="dd.MM.yyyy'_'hh.mm.ss'.log'" />
            <staticLogFileName value="false" />
            <rollingStyle value="Size" />
            <maximumFileSize value="20MB" />
            <maxSizeRollBackups value="100" />
            <layout type="log4net.Layout.PatternLayout">
                <header value="[Header] " />
                <footer value="[Footer] " />
                <conversionPattern value="%date %-5level %logger ${COMPUTERNAME} - %message%newline" />
            </layout>
        </appender>

As you can see I had the date and time pattern with the date and time and the rolling style set to size.

This didn't quite work in fact the resulting file name was 'GaetanosLog_'. After some research I realised that to have the date in the log file name I had to set the rollingStyle to Date.


<rollingStyle value="Date" />

All good so far the log file had the date and time in it!! Kind of... I soon realised that every minute a new log file was created....obviously this was due to the rolling style.

So to fix this issue I decided to take a different approach and to set dynamically the log file name.

Firstly I've modified my log4net configuration


	<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
		<file type="log4net.Util.PatternString" value="C:\temp\%property{LogFileName}.log" />
		<appendToFile value="true" />
		<staticLogFileName value="false" />
		<rollingStyle value="Size" />
		<maximumFileSize value="20MB" />
		<maxSizeRollBackups value="100" />
		<layout type="log4net.Layout.PatternLayout">
			<header value="[Header] " />
			<footer value="[Footer] " />
			<conversionPattern value="%date %-5level %logger ${COMPUTERNAME} - %message%newline" />
		</layout>
   </appender>

And in code I set the property LogFileName


	 var fileName = string.Format("PasswordMigrator_{0}", DateTime.Now.ToString("yyyy.MM.dd.hh.mm.ss"));
	 GlobalContext.Properties["LogFileName"] = fileName;
	 log4net.Config.XmlConfigurator.Configure();

Problem solved it now works perfectly!





Dec6

Back To List