Logging method name

Topics: General discussion, Logging Application Block
Jun 7, 2012 at 1:23 PM

We are trying to port logging code over from log4net to Enterprise library 5 logging. In log4net and nlog you have the ability to include the method name in the log file. This is as simple as including a %M in the patternLayout. I can't seem to find a way to do this with TextFormatter ? Could someone let me know if this is possible and how I can do this ?

Jun 8, 2012 at 7:06 AM

The LogCallHandler provides this functionality but it's probably not what you want since that is logging method entries and exits and you probably just want the method where the LogWriter was called from.

The other alternative would be to add that information to either the ExtendedProperties or use the TraceLogEntry class instead of the usual LogEntry.  In this (un-optimized) example I get the calling method from the StackFrame (this is a relatively expensive operation) and use the TraceLogEntry class:

    public class MyLogger
        public void Log(string message)
            TraceLogEntry le = new TraceLogEntry()
                    Message = message,
                    MethodName = new StackFrame(1, true).GetMethod().Name,
                    Categories = new string[] { "General" }

            var logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

    public class MyClass
        public void DoSomething()
            var logger = new MyLogger();

Then in the formatter you can reference the method name using the syntax {property(MethodName)}:

            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                template="MethodName: {property(MethodName)}&#xA;Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}"
                name="Text Formatter" />

Randy Levy
Enterprise Library support engineer