log4net的和额外的领域领域、log4net

2023-09-03 12:14:13 作者:曲終ん散

是否可以插入额外的字段到数据​​库中,并使用他们在log4net的?我有一个用户ID,我想有一个额外的字段在日志表​​

我在加入该领域的 log4net.config

 <参数>
    <参数名称值=@用户ID/>
    < D​​BTYPE值=GUID/>
    <布局类型=log4net.Layout.RawPropertyLayout/>
< /参数>
 

但我怎么更新的ILog 接口,支持额外的数据库字段。所以我可以,例如日志:

  log4net.LogManager.GetLogger(LOGNAME)致命的(消息,异常,用户ID);
 

解决方案 log4net 不生成日志 log4net的配置和简单使用

您可以使用背景功能log4net的。基本上,它允许您设置的属性,你就可以在你的日志的appender使用。您可以设置这些属性在不同范围(全球,螺纹等)。你的情况我觉得你可以去(例如,只在用户已经登录):

  log4net.ThreadContext.Properties [用户id] =用户id;
 

在您的配置文件,然​​后你可以使用这个属性,并将其添加到日志附加目的地。我认为这将是这样的AdoNetAppender

 <参数>
    <参数名称值=@用户ID/>
    < D​​BTYPE值=GUID/>
    <布局类型=log4net.Layout.PatternLayout>
        < conversionPattern值=%属性{用户ID}/>
    < /布局>
< /参数>
 

请注意,我没有任何编译上面的代码片段,所以他们可能需要一些调整,但它应该给你如何可以解决的总体思路。

您可以阅读更多关于此这里。

诗。我认为,这是指在第一个答案的MDC.Set已经过时了。

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

解决方案

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.