2

I have a program in C# and use the log4net library for logging.

I am trying to log the program start time in each line of log in the entire program:

class MyProgram
{
    static DateTime startTime;
    static void Main()
    {
        startTime = DateTime.Now;
        Log.Info(startTime + "Program started");

        MyMethod1();
        //...
    }

    static void MyMethod1()
    {
        Log.Info(startTime + "method1 step1 ");
        //code
        Log.Info(startTime + "method1 step2");
    }    
}

log4net configuaration

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Logs\\Job.json" />

      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maximumFileSize value="20MB" />
      <maxSizeRollBackups value="10" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
        <decorator type="log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json" />
        <member value="startTime:%property{ApplicationStartTime}"/>
        <member value="date:date" />
        <member value="level:level" />
        <member value="logger:logger" />
        <member value="message:messageObject" />
        <member value="exception:exception" />
      </layout>     
    </appender>

Instead of appending it manually to each line, can I configure log4net to add the start time of the program to each log line automatically?

DoIt
  • 3,270
  • 9
  • 51
  • 103

2 Answers2

5

You can use log4net.GlobalContext to set global properties. like this:

   static void Main()
    {
        log4net.GlobalContext.Properties["ApplicationStartTime"] = DateTime.Now;
    (...)

and then access it like this in your log configuration

%property{ApplicationStartTime}

Here is some more reading, here is a similar question.

For log4net.Ext.Json, you can refer to custom properties in this manner:

<!-- json property named after custom property -->
<member value="ApplicationStartTime"/> 
<!-- json property with explicit name -->
<member value="startTime:ApplicationStartTime"/>
Tewr
  • 3,713
  • 1
  • 29
  • 43
  • I tried it but I couldnt get the parameter in the logs. Added log4net config to the question – DoIt May 03 '18 at 18:09
4

Create a method wrapper around the log4net log method, that takes a message and forwards it to the log4net log method, but prepends the startTime to it for you.

var startTime = DateTime.Now.ToString();

void Log(string message)
{
  Log.Info($"{startTime}: {message}");
}

Alternatively you can create an extension method:

public static class LoggerExtensions
{
    public static void LogWithStartTime(this Logger self, string message)
    {
        var startTime = Global.GetStartTime();

        self.Log($"{startTime}: ${message}");
    }
}
mariocatch
  • 8,305
  • 8
  • 50
  • 71