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 conversion pattern, it just prints Debug, which is the wrapper method name.
Is there a way to print the full method stack?
E.g.
Instead of Debug --> SomeLoggingActionInSomeClass.Debug?
Wrapper class code:
public static class Logger
{
private static ILog _log;
static Logger()
{
log4net.Config.XmlConfigurator.Configure();
_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
public static void Init()
{
}
public static void Debug(string message)
{
_log.Debug(message);
}
Calling Class Code:
W6CustomizationLogger.Logger.Debug("Backup(): START");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With