Florian Peschka Florian Peschka - 1 year ago 84
ASP.NET (C#) Question

Add an appender for a portion of code

For a certain portion of my code, I need to log all messages to a second file, specific to each instance of the action completed in two classes.

These classes (

) both have the following logger definition:

private static ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Both also have this method:

public void AddAppender(IAppender appender)

The whole project (ASP.NET WebForms) logging is initialized in the AssemblyInfo.cs:

[assembly: XmlConfigurator]

Now, when the user triggers a certain action, this happens:

var logFile = new FileInfo(ConfigurationManager.AppSettings["uploadDir"] + "/" + importId + "_log.txt");
var appender = new FileAppender() {
Threshold = Level.Info,
Layout = new PatternLayout("%message%newline"),
File = logFile.FullName

var parser = new Parser(...);
var candidates = parser.Parse(File.ReadAllLines(uploadFile.FullName));

var importer = new Importer(...);
importer.Import(candidates, false, ignoreWarnings.Checked);

My expectation would be, that a file will be created at the
location, that would contain all
and above message from either of the two classes.

This, however, is not the case - no file is created at all.

What am I doing wrong and how can I make this work?

Answer Source

Per the documentation of FileAppender:

This appender will first try to open the file for writing when ActivateOptions is called. This will typically be during configuration. If the file cannot be opened for writing the appender will attempt to open the file again each time a message is logged to the appender. If the file cannot be opened for writing when a message is logged then the message will be discarded by this appender.

This documentation is slightly ambiguous, since it seems to imply the file will be opened when you attempt to log a message in all cases, but this isn't true -- unless you call ActivateOptions, the appender is never considered ready for appending.