Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you make log4net output to current working directory?

Tags:

log4net

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

In other words, if I run ..\myapp.exe, I don't want the log files in ..\ I want them in .\

like image 983
Ken Goodridge Avatar asked Dec 17 '09 15:12

Ken Goodridge


People also ask

Does log4net create directory?

When using a file appender, the destination folder does not have to exist. Log4net creates the folder. Using an administrator account, connect to the Coveo Master server.

What is RollingFileAppender in log4net?

"When set to Once the log file will be rolled when the appender is configured. This effectively means that the log file can be rolled once per program execution. So, when you set your RollingFileAppender to "once", then every time you execute your program, a new log file will be created.


2 Answers

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.

like image 115
Ken Goodridge Avatar answered Sep 22 '22 09:09

Ken Goodridge


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")));
like image 44
Otávio Décio Avatar answered Sep 25 '22 09:09

Otávio Décio