Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Log4Net - dynamically change log directory programmatically

I read through most of the related topics regarding changing log directory programmatically, but the answers were a little advanced.

My problem is trying to dynamically change where my log file is saved from my C# application. I have a text box with a browse button to choose where it should be saved.

Anyone have an idea or can point me in the right direction with some code? I've tried playing around with similar ideas but can't seem to get it right.

like image 769
Jeff Avatar asked Jul 08 '10 14:07

Jeff


2 Answers

If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way

file type="log4net.Util.PatternString" value="%property{LogFileName}.txt"

and then in the code before calling log4net configure, set the new path like below

log4net.GlobalContext.Properties["LogFileName"] = @"E:\file1"; //log file path 
log4net.Config.XmlConfigurator.Configure();

So if your requirement is changing the log directory so frequently then update the property value each time followed by .Configure() as well.

like image 139
Avijit Chatterjee Avatar answered Nov 01 '22 07:11

Avijit Chatterjee


Though the Question asked is quite Old, But I happened to find a really nice solution here, that worked for me.

public static bool ChangeLogFileName(string appenderName, string newFilename)
{            
  var rootRepository = log4net.LogManager.GetRepository();
  foreach (var appender in rootRepository.GetAppenders())
  {
    if (appender.Name.Equals(appenderName) && appender is log4net.Appender.FileAppender)
    {
      var fileAppender = appender as log4net.Appender.FileAppender;
      fileAppender.File = newFilename;
      fileAppender.ActivateOptions();
      return true;  // Appender found and name changed to NewFilename
    }
  }
  return false; // appender not found
}
like image 32
V.Aggarwal Avatar answered Nov 01 '22 08:11

V.Aggarwal