Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4Net and extra fields

Tags:

.net

log4net

Is it possible to insert extra fields into the database and use them in log4net? I have a UserId I would like to have in an extra field in the log-table.

I have added the field in the log4net.config:

<parameter>
    <parameterName value="@userid" />
    <dbType value="guid" />
    <layout type="log4net.Layout.RawPropertyLayout" />
</parameter>

But how do I update the ILog interface to support the extra database field. So I could for example log:

 log4net.LogManager.GetLogger("logname").Fatal(message, exception, userid);
like image 791
Dofs Avatar asked Nov 25 '09 07:11

Dofs


1 Answers

You could use the "context" feature in log4net. Basically it allows you to set properties that you can then use in your log appender. You can set these properties at different scopes (Global, Thread etc.). In your case I think you could go (for instance, just after the user has logged in):

log4net.ThreadContext.Properties["userid"] = userid;

In your configuration file, you could then use this property and add it to the logging appender. I think it would be something like this for the AdoNetAppender

<parameter>
    <parameterName value="@userid" />
    <dbType value="guid" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{userid}" />
    </layout>
</parameter>

Please note that I have not compiled any of the snippets above, so they might need some tweaking, but it should give you a general idea of how this could be solved.

You can read more about this here.

Ps. I think that the MDC.Set that is referred to in the first answer is obsolete.

like image 108
tmatuschek Avatar answered Oct 31 '22 16:10

tmatuschek