Search code examples
asp.net-corelog4netfluentd

Bind Custom Properties to LoggingEvent Object in Log4Net


I am using log4net and I am trying to figure out the best way, or if there is anyway, to bind custom fields to the LoggingEvent object, that is used in the Append override method of the AppenderSkeleton.

For example, this could be a guid property to add to the other properties such as level, renderedMessage, etc.

However, I am planning on using the Log4net.Appenders.Fluentd with the log4net.Ext.Json, so the appender in the xml would look something like this:

<appender name="Fluentd" type="Log4net.Appenders.Fluentd.FluentdAppender, Log4net.Appenders.Fluentd">
    <Host>127.0.0.1</Host>
    <Port>24224</Port>
    <Tag>YourTagHere</Tag>
    <NoDelay>false</NoDelay>
    <ReceiveBufferSize>8192</ReceiveBufferSize>
    <SendBufferSize>8192</SendBufferSize>
    <SendTimeout>1000</SendTimeout>
    <ReceiveTimeout>1000</ReceiveTimeout>
    <LingerEnabled>true</LingerEnabled>
    <LingerTime>1000</LingerTime>
    <EmitStackTraceWhenAvailable>true</EmitStackTraceWhenAvailable>
    <IncludeAllProperties>false</IncludeAllProperties>
    
  <!--json formatted log4net logging-->
  <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
    <decorator type="log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json" />
    <member value="date:date" />
    <member value="level:level" />
    <member value="message:messageObject" />
  </layout> 
</appender>

I was hoping there would be something like this in the end:

<!--json formatted log4net logging-->
<layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
    <decorator type="log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json" />
    <member value="date:date" />
    <member value="level:level" />
    <member value="message:messageObject" />
    <member value="guid:guid" />
</layout>

Is this something I would have to some how carry out in the Log4net.Appenders.Fluentd source code?


Solution

  • You can use the ThreadContext to add a custom property to the LoggingEvent object that is passed into the Append override method of the AppenderSkeleton and the Format override method of the LayoutSkeleton.

    Set it:

    ThreadContext.Properties["my_custom_prop"] = "my custom property"
    

    Then retrieve it:

    var prop = evt.GetProperties()["my_custom_prop"].ToString();