I created a c# wrapper for log4net.
It has Debug() and Error() methods.
I want to log the method name which logs the record, but If I try to use the %method conv
If you really must use a wrapper class, then the best way is to get the calling method in the wrapper and then store that as a property:
var stackFrames = new StackTrace().GetFrames();
var callingframe = stackFrames.ElementAt(1);
var method = callingframe .GetMethod().Name;
// Store in log4net ThreadContext:
ThreadContext.Properties["method"] = method;
Then in the layout reference the property:
<conversionPattern value = ""Method: %property{method}"" />
There is also a way to resolve this just using the layout, you would use %stacktrace in your layout to get the call stack, specifically %stacktrace{2}
to get the calling method.
Note that when you use this, the whole stack is logged, including the wrapper method.
Example output:
log4net.Tests.Stacktrace_Tests.StackTrace_In_PatternLayout > log4net.Tests.Wrapper.Debug
Scrap that wrapper.
Configuration
To initialize logging you can instead configure it quite easily in your startup project.
3 Add the following:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Screenshot:
Usage
Now in your classes simply add:
public class YourClass
{
private ILog _logger = LogManager.GetLogger(typeof(YourClass));
// [....]
}
And in your log4net.config
you can now use the logger
property in the output:
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-7level %-40logger %message%newline" />
</layout>
Which will print the namespace and type name on every log line (-7
and -40
pads the names so that I get straight columns).
The other great thing is that you can also use a filter on the namespace (to make all database classes log to "databases.log" etc).
<appender name="DatabaseAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\Logs\MyApp\Database.log" />
<rollingStyle value="Composite" />
<datePattern value=".yyyy-MM-dd'.log'" />
<appendToFile value="true" />
<maximumFileSize value="50MB" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level@%thread [%logger] %message%newline" />
</layout>
<!-- Namespace/Type filter -->
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="CompanyName.DatabaseNamespace"/>
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
</appender>
You can also use %type{1}
instead if %logger
to get only the class name.