log4net filepaths and how to get at Appenders at runtime
Just a note of something simple and silly enough that I shouldn't forget it again: Filepaths in log4net configurations still have to escape the DOS separator backslash. I know it should be obvious, you use \ in a text file, you escape it.
Well, i was too used to the @"c:\foo\bar.txt" syntax from C# that when i took the path out of the code and into the log4net XML config, i left it in the c:\foo\bar.txt format. I wasn't able to wrap a debugger around the deployed code and couldn't figure out why my logger wasn't writing. I figured out how to get to the currently available appenders at runtime and wrote that to the web page trace and seeing that there was no filename for the RollingFile appender, smacked me in the head with the "escape the backslash, stupid".
The silly part out of the way, this did give me some useful insight into log4net internals. So to get at the configured appenders you can do this:
// Just grabbing the first logger, since we want to use it to grab it's parent, // the root logger log4net.Repository.Hierarchy.Logger logger = (log4net.Repository.Hierarchy.Logger)log.Logger.Repository.GetCurrentLoggers()[0]; Console.WriteLine("Logger: {0}",logger.Name); // foreach( log4net.Appender.IAppender appender in logger.Parent.Appenders ) { Console.WriteLine(" Appender: {0}",appender.Name); // just checking for RollingFile here, but could just as well check for all other appenders if(appender.GetType() == typeof(log4net.Appender.RollingFileAppender)) { log4net.Appender.RollingFileAppender rolling = (log4net.Appender.RollingFileAppender)appender; Console.WriteLine(" Rolling File: {0}",rolling.File); }
Mind you this is just a place to get started from. It does make a number of assumptions you shouldn't make in production code. It is good enough though to help you debug log4net behavior.

2 Comments:
I do not know if it is still relevant, but recent version of log4net does not require escaping backslash in its configuration file
Thanks for the info. log4net is one of those components that just works, so i haven't even bothered following its revisions, but that sounds like a feature worth getting the current version for
Post a Comment
<< Home