Search code examples
c#log4netlog4net-configuration

How to add parameters to Log4Net while saving as text file


I use log4net.Appender.RollingFileAppender.

I save my logs to a textfile. I want to customize Properties Values.

            <log4net debug="true">
            <appender name="file" type="log4net.Appender.RollingFileAppender, log4net">
              <file value="Log.txt" />
              <appendToFile value="true" />
              <rollingStyle value="Size" />
              <maxSizeRollBackups value="10" />
              <maximumFileSize value="1MB" />
              <staticLogFileName value="true" />
              <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %level %logger [%property{NDC}] - %message%newline" />
              </layout>
            </appender>
            <root>
              <level value="ALL" />
              <appender-ref ref="file" />
            </root>
          </log4net>

This is my class:

public static class log4netPark
{
    private static ILog _logger = null;

    private static log4net.ILog Logger
    {
        get
        {
            if (_logger == null)
            {
                _logger = LogManager.GetLogger(typeof(log4netPark));
                log4net.Config.XmlConfigurator.Configure();
            }
            return _logger;
        }
    }

    public static void Info(string Message, LogType tip)
    {
        Logger.Info(Message);
    }

    public static void Error(string Message, Exception ex, LogType tip)
    {
        Logger.Error(Message, ex);
    }
}

It is saving to txtfile like this.

2018-04-05 18:37:23,772 [1] INFO IK_DL.log4netPark [(null)] - User logged in.

I try this codeblocks into Info method but any of this cant work:

GlobalContext.Properties["LOG_TYPE"] = 3;
GlobalContext.Properties["name"] = "tryThisOne";
ThreadContext.Stacks["logger"].Push("LoggerNameTrying");
LogicalThreadContext.Properties["&thread"] = 13;

When using AdoNetAppender, we can add parameters. Is it possible RollingFileAppender or can I do this with codeblockS?


Solution

  • You'll have to mention the properties in your format string. So if you want the "LOG_TYPE" property to be printed, change your pattern:

    <conversionPattern value="... [%property{LOG_TYPE}] - %message%newline" />