C# 你如何通过 log4net 记录机器名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/162810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:18:52  来源:igfitidea点击:

How do you log the machine name via log4net?

c#.netlogginglog4net

提问by Stephen Tolton

I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.

我使用 Log4Net 和 AdoNetAppender 将来自简单系统托盘应用程序的消息记录到 SQL Server 2005 数据库中。

I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.

我想记录机器名称和日志消息,因为这个应用程序将在多台机器上运行,我需要知道消息来自哪一台。

But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.

但是,我找不到通过我与 appender 一起使用的 log4net.Layout.PatternLayout 公开这些信息的方法。

Is there a way to log the machine name via log4net in this manner?

有没有办法以这种方式通过 log4net 记录机器名称?

采纳答案by Thad

You can use the pre-populated property log4net:HostName, for example:

您可以使用预先填充的属性log4net:HostName,例如:

<conversionPattern value="%property{log4net:HostName}" />

This way you don't need to populate the MDC.

这样您就不需要填充 MDC。

回答by Thad

you can create a parameter similar to the following:

您可以创建类似于以下内容的参数:

<parameter>
  <parameterName value="@machine" />
  <dbType value="String" />
  <size value="255" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%X{machine}" />
  </layout>
</parameter>

Then add this line before writing to the log: MDC.Set("machine", Environment.MachineName);

然后在写入日志之前添加这一行: MDC.Set("machine", Environment.MachineName);