Log4Net and extra fields

不打扰是莪最后的温柔 提交于 2020-01-01 04:39:04

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/1795310/log4net-and-extra-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!