103

I use the log4net.Appender.AdoNetAppender appender.
My log4net table are the following fields [Date],[Thread],[Level],[Logger],[Message],[Exception]

I would need to add another field to the log4net table (e.g SalesId), but how would I specify in my xml and in code to log the "SalesId" when logging a Error or Info message?

e.g. log.Info("SomeMessage", SalesId)

Here's the log4net xml

  <appender name="SalesDBAppender" type="log4net.Appender.AdoNetAppender">
    <bufferSize value="1" />
    <connectionType value ="System.Data.SqlClient.SqlConnection" />
    <connectionString value="Data Source=..." />
    <commandText value="INSERT INTO Log4Net ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
    <parameter>
      <parameterName value="@log_date" />
      <dbType value="DateTime" />
      <layout type="log4net.Layout.RawTimeStampLayout" />
    </parameter>
    <parameter>
      <parameterName value="@thread" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level" />
      <dbType value="String" />
      <size value="50" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@logger" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@message" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@exception" />
      <dbType value="String" />
      <size value="2000" />
      <layout type="log4net.Layout.ExceptionLayout" />
    </parameter>
  </appender>
Eminem
  • 7,206
  • 15
  • 53
  • 95

3 Answers3

199

1) Modify the command text: INSERT INTO Log4Net ([Date],[Thread],[Level],[Logger],[Message],[Exception],[MyColumn]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception, @CustomColumn)

2) Add the parameter definition for the custom column:

<parameter>
   <parameterName value="@CustomColumn"/>
   <dbType value="String" />
   <size value="255" />
   <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%property{CustomColumn}" />
  </layout>
</parameter>

3) Then use one of log4net’s contexts to transfer values to the parameter:

// thread properties...
log4net.LogicalThreadContext.Properties["CustomColumn"] = "Custom value";
log.Info("Message"); 

// ...or global properties
log4net.GlobalContext.Properties["CustomColumn"] = "Custom value";
Marcelo De Zen
  • 9,439
  • 3
  • 37
  • 50
  • 2
    Can someone suggest which Context is best for logging browser capabilities. – VivekDev Mar 10 '15 at 12:20
  • 1
    @DumbDev, usually you will use the Thread context. The GlobalContext is useful to set properties that do not change very often. – Marcelo De Zen Mar 10 '15 at 19:06
  • 1
    You should be very careful when using the ThreadContext in a Web Application though since these tend to jump threads and the ThreadContext will not be moved along with it. – Robba Jan 26 '16 at 08:59
  • @Robba - Could you explain a little further? Does the thread context issue negate this as a good method to log User Info? Should the GlobalContext be used instead? – webworm Mar 08 '16 at 13:27
  • As the name implies, the ThreadContext is bound to the thread. When you're using the async/await pattern it is very likely that the code after the await will run on a different thread and can thus lead to very odd behaviour when you're using the ThreadContext property. – Robba Mar 11 '16 at 15:29
  • Any idea if LogicalThreadContext is ok when being used with Tasks and async (meaning, in scenarios where it's not assured that current thread will continue on processing request)? – the berserker Jun 06 '16 at 13:55
  • 5
    @theberserker `LogicalThreadContext` is ok to use with Tasks, It's not ok to use `ThreadContext` though, because it's always bounded to a particular thread. – Marcelo De Zen Jun 09 '16 at 16:07
  • 1
    @devundef , thanks for this. After days of searching, I've finally come across this. Awesome. – Just Rudy Mar 24 '17 at 20:55
  • 7
    It's my opinion, but it seems a bit weird this way, I expected an overload that takes more arguments to add to the new LoggingEvent instance.. – A77 Jul 12 '17 at 10:08
  • @A77 I was hoping for something like that too. Found any solutions? – JKL Jul 11 '18 at 09:28
  • @Salvatore'Lucky'Luciano Nope unfortunately, finally implemented this way :/ – A77 Jul 11 '18 at 15:42
  • @MarceloDeZen Where do I add the custom column to the Properties? Must I add the column everywhere I'm logging? – Ron Apr 16 '19 at 14:17
  • I'm afraid so @Ron. – Marcelo De Zen May 16 '19 at 14:55
11

Three types of logging context available in Log4Net.

  1. Log4Net.GlobalContext :- This context shared across all application threads and domains.If two threads set the same property on GlobalContext, One Value will override the other.

  2. Log4Net.ThreadContext :- This context scope limited to calling thread. Here two threads can set same property to different values without overriding to each other.

  3. Log4Net.ThreadLogicalContext :- This context behaves similarly to the ThreadContext. if you're working with a custom thread pool algorithm or hosting the CLR, you may find some use for this one.

Add the following code to your program.cs file:

static void Main( string[] args )
{
    log4net.Config.XmlConfigurator.Configure();
    log4net.ThreadContext.Properties[ "myContext" ] = "Logging from Main";
    Log.Info( "this is an info message" );
    Console.ReadLine();
}

2) Add the parameter definition for the custom column:

  <log4net>      
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger (%property{myContext}) [%level]- %message%newline" />
      </layout>
    </appender> 
  </log4net>
piyush gupta
  • 111
  • 1
  • 2
4

Here is a working version with some personalized preferences. I added a custom column for storing a generated exception code.

1) Add your custom column(exceptionCode here) to Log4net config:

<commandText value="INSERT INTO Log([Date],[Thread],[Level],[Logger],[Message],[Exception],[ExceptionCode]) 
VALUES (@log_date, @thread, @log_level, @logger, @message, @exception,@exceptionCode)" />

<parameter>
    <parameterName value="@exceptionCode" />
    <dbType value="String" />
    <size value="11" />
    <layout type="Common.Utils.LogHelper.Log4NetExtentedLoggingPatternLayout">
        <conversionPattern value="%exceptionCode{Code}" />
    </layout>
</parameter>

2) Log4NetExtentedLoggingCustomParameters.cs

namespace Common.Utils.LogHelper
{
    public class Log4NetExtentedLoggingCustomParameters
    {
        public string ExceptionCode { get; set; }

        public string Message { get; set; }

        public override string ToString()
        {
            return Message;
        }
    }
}

3) Log4NetExtentedLoggingPatternConverter.cs

namespace Common.Utils.LogHelper
{
    public class Log4NetExtentedLoggingPatternConverter : PatternConverter
    {
        protected override void Convert(TextWriter writer, object state)
        {
            if (state == null)
            {
                writer.Write(SystemInfo.NullText);
                return;
            }

            var loggingEvent = state as LoggingEvent;
            var messageObj = loggingEvent.MessageObject as Log4NetExtentedLoggingCustomParameters;

            if (messageObj == null)
            {
                writer.Write(SystemInfo.NullText);
            }
            else
            {
                switch (this.Option.ToLower()) //this.Option = "Code"
                {
                    case "code": //config conversionPattern parameter -> %exceptionCode{Code}
                        writer.Write(messageObj.ExceptionCode);
                        break;  
                    default:
                        writer.Write(SystemInfo.NullText);
                        break;
                }
            }
        }
    }
}

4) Log4NetExtentedLoggingPatternLayout.cs

namespace Common.Utils.LogHelper
{
    public class Log4NetExtentedLoggingPatternLayout : PatternLayout
    {
        public Log4NetExtentedLoggingPatternLayout()
        {
            var customConverter = new log4net.Util.ConverterInfo()
            {
                Name = "exceptionCode",
                Type = typeof(Log4NetExtentedLoggingPatternConverter)
            };

            AddConverter(customConverter);
        }
    }
}

5) Logger.cs // Enjoy your logger with new column! :)

namespace Common.Utils.LogHelper
{
    public class Logger
    {
        static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static string LogError(string message, Exception exception = null)
        {
            var logWithErrCode = GetLogWithErrorCode(message);
            Logger.Error(logWithErrCode, exception);
            return logWithErrCode.ExceptionCode;
        }

        private static Log4NetExtentedLoggingCustomParameters GetLogWithErrorCode(string message)
        {
            var logWithErrCode = new Log4NetExtentedLoggingCustomParameters();
            logWithErrCode.ExceptionCode = GenerateErrorCode(); //this method is absent for simplicity. Use your own implementation
            logWithErrCode.Message = message;
            return logWithErrCode;
        }
    }
}

references:

http://blog.stvjam.es/2014/01/logging-custom-objects-and-fields-with

Ali Karaca
  • 3,365
  • 1
  • 35
  • 41