Situation: I want to show the method and line number for the code that logs the message. The problem is that I have an intermediate class that calls the log4net logger. Unfortunately, due to existing architectural problems, I cannot do away with this intermediate class. As a result, I always see that the method and line number are in an intermediate class. Not what I want.
So, I tried to create my own PatternLayoutConverter template in accordance with this question:
Does support log4net, including call stack, in the log message
I also configure log4net programmatically, because, again for architectural reasons, using an XML configuration file is not possible (I also find it funny that the preferred and only documented way to configure log4net is through a silly XML file, but the topic is for another discussion). Therefore, I followed this topic.
How to program log4net from scratch (no configuration)
Everything works fine, except that my custom converter is never called. Here is the code for the custom converter:
public class TVPatternLayout : PatternLayout {
public TVPatternLayout() {
this.AddConverter("logsite", typeof(TVPatternLayoutConverter));
}
}
public class TVPatternLayoutConverter : PatternLayoutConverter {
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) {
StackTrace st = new StackTrace();
int idx = 1;
while(st.GetFrame(idx).GetMethod().DeclaringType.Assembly == typeof(LogManager).Assembly)
idx++;
writer.Write(String.Format("{0}.{1} (line {2})", st.GetFrame(idx).GetMethod().DeclaringType.Name, st.GetFrame(idx).GetMethod().Name,
st.GetFrame(idx).GetFileLineNumber()));
}
}
And here is the code where I set up the registrar:
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Configured = false;
RollingFileAppender appender = new RollingFileAppender();
appender.Name = loggerName;
appender.File = realPath;
appender.AppendToFile = true;
appender.MaximumFileSize = "8000";
appender.MaxSizeRollBackups = 2;
TVPatternLayout patternLayout = new TVPatternLayout();
patternLayout.ConversionPattern = logFormat;
appender.Layout = patternLayout;
appender.ActivateOptions();
hierarchy.Root.AddAppender(appender);
hierarchy.Root.Level = Level.All;
hierarchy.Configured = true;