log4net is an open source library used for logging the information during program execution.It is one of the most popular logging libraries used in c#.
Sometimes we need to decide and set the location of the log file at runtime.To set the log4net log file path dynamically in c# is as simple as defining a property in the config file and setting the property value at
runtime in code
We can use following steps to implement this scenario.
Suppose you have configured log4net in config file as:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Sample.log" /> <appendToFile value="true" /> <maxSizeRollBackups value="100" /> <rollingStyle value="Size" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date - %message-%newline" /> </layout> </appender> <logger name="SampleAppender"> <level value="DEBUG" /> <appender-ref ref="RollingFileAppender" /> </logger>
- Replace the <file value=”Sample.log” /> element with the below element.The PatternString is a string representing a pattern which could contain different values.One pattern is property which represents a property which is set at runtime.Here we are including a LogFileName property.
<file type="log4net.Util.PatternString" value="%property{LogFileName}.log" />
Please note that we have used %property{LogFileName} to dynamically set the value attribute of the file element.%property{LogFileName} indicates that LogFileName we will set it dynamically.
2. Set the LogFileName value in code.
ILog logger = LogManager.GetLogger("SampleAppender"); log4net.GlobalContext.Properties["LogFileName"] = "MyLog"; XmlConfigurator.Configure();
For the basics of implementing log4net in your application please refer Introduction to log4net in c#
frank says
This was most helpful. Well met.
Nagarjuna says
This is brilliant.