Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the Log file path programmatically in log4net?

Tags:

I am using %property% to set the output file path in the Log4Net configuration file. A log file will be created in the APP data folder every time when the application launches. I am using the Composite rolling style for rolling the files.

But now my requirement is to roll/change the file path based on some user interactions in the application. How can I achieve this, can anyone suggest me to achieve this.

  1. How to roll the file in c# code. The expected behavior is similar to rolling based on Size and date.
  2. What is the c# code to change the output file path in Log4Net in between program execution?

Please let me know if my requirement is not clear.

Thanks.

like image 357
Venkat Avatar asked Oct 11 '17 06:10

Venkat


People also ask

Where do log4net logs go?

You can configure the log4net. config file to create log files. The file is located in the webroot\App_data directory of the installation.

What is RollingFileAppender in log4net?

RollingFileAppender can roll log files based on size or date or both depending on the setting of the RollingStyle property. When set to Size the log file will be rolled once its size exceeds the MaximumFileSize.


1 Answers

You have 2 questions:

  1. I'm not aware if this is possible. I guess the roll to next name is private in the rolling file appender. You can look in the src to see if you can access it. If not you can inherit from the RollingFileAppender and add your own implementation. You can get the appenders on runtime by:

code:

  LogManager.GetRepository().GetAppenders();
  1. Using a property is the right way. Your configuration should look like this:

config:

 <appender name="YourAppender" type="log4net.Appender.RollingFileAppender"> 
    <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
 </appender>

Important is the type="log4net.Util.PatternString". Set the property before initializing log4net.

log4net.GlobalContext.Properties["LogName"] = name;
like image 76
Peter Avatar answered Oct 11 '22 14:10

Peter