开发者

how do you make log4net output to current working directory?

开发者 https://www.devze.com 2022-12-14 11:53 出处:网络
Is it possible to have log4net put its log files relative to the current working directory instead of the directory where the application resides?

Is it possible to have log4net put its log files relative to the current working directory instead of the directory where the application resides?

开发者_如何学GoIn other words, if I run ..\myapp.exe, I don't want the log files in ..\ I want them in .\


I ended up looking at the log4net source and determined I can implement my own appender that extends FileAppender and overrides the File property.

class CWDFileAppender : FileAppender
{
    public override string File
    {
        set
        {
            base.File = Path.Combine(Directory.GetCurrentDirectory(), value);
        }
    }
}

I just use CWDFileAppender in my configuration.


Not possible from the config file, as per here. It may be possible if you are configuring it manually from inside your program though:

public static log4net.Appender.IAppender CreateFileAppender(string name,
string fileName)
{
  log4net.Appender.FileAppender appender = new
log4net.Appender.FileAppender();
  appender.Name = name;
  appender.File = fileName;
  appender.AppendToFile = true;

  log4net.Layout.PatternLayout layout = new
log4net.Layout.PatternLayout();
  layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
  layout.ActivateOptions();

  appender.Layout = layout;
  appender.ActivateOptions();

  return appender;
}

You can then associate it with the logger as follows:

AddAppender("Log4net.MainForm", CreateFileAppender("FileAppender",   
Path.Combine(Directory.GetCurrentDirectory(), "foo.log")));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号