DoIt
DoIt

Reputation: 3448

Appending the program start time to each log line

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?

Upvotes: 2

Views: 454

Answers (2)

Tewr
Tewr

Reputation: 3853

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"/>

Upvotes: 5

mariocatch
mariocatch

Reputation: 8703

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}");
    }
}

Upvotes: 4

Related Questions