Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Name in log4net C#

Tags:

c#

.net

log4net

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");
like image 314
Y.S Avatar asked Feb 10 '23 08:02

Y.S


1 Answers

Scrap that wrapper.

Configuration

To initialize logging you can instead configure it quite easily in your startup project.

  1. Click on the arrow next to your "Properties" on your startup project in Solution explorer
  2. Double click on assembly info

enter image description here

3 Add the following:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Screenshot:

enter image description here

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.

like image 166
jgauffin Avatar answered Feb 12 '23 02:02

jgauffin