我想用静态信息扩展我的日志文件,比如我的软件运行的操作系统。
有没有办法只为每个创建的文件注入一次这个信息而不是每个日志条目?
这就是我目前的做法(但这会导致一遍又一遍地输出信息 - 这是静态信息所必需的)
GlobalContext.Properties["**evInfoOsPlatform**"] = string.Format("OS Platform: {0}", Environment.OSVersion.Platform);
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%thread] %level
%logger - %message%newlineOperating System Version: %property{
**evInfoOsPlatform**}%newline%exception"/>
</layout>
我想要的效果是一个看起来像这样的日志文件:
Static information:
OS Version: Windows 8.1.0101934 32-bit
Culture Info: en-US
Domainname: RandomDomain
Username: Emil
Userrights: Admin
Messages:
//now all the messages should be printed...
此代码用于C#.Net 4.5 WPF环境。
希望你能提供帮助。
答案 0 :(得分:1)
如果您正在使用RollingFileAppender,请查看this question - 基本上您要创建一个继承自RollingFileAppender的类,并覆盖WriteHeader
方法,仅将标头写入每个文件一次
This answer通过子类化log4net.Layout.PatternLayout
将这些放在一个例子中:
namespace MyAssembly.log4net.Header.Example
{
public class HeaderAppender : RollingFileAppender
{
protected override void WriteHeader()
{
if (LockingModel.AcquireLock().Length == 0)
{
base.WriteHeader();
}
}
}
public class HeaderPatternLayout : PatternLayout
{
public override string Header
{
get
{
StringBuilder headerBuilder = new StringBuilder();
headerBuilder.AppendLine("Static information");
headerBuilder.AppendLine("OS Version: "
+ Environment.OSVersion);
headerBuilder.AppendLine("Culture Info: "
+ CultureInfo.CurrentCulture);
headerBuilder.AppendLine("[Etc] ");
headerBuilder.AppendLine();
headerBuilder.AppendLine("Messages:");
return headerBuilder.ToString();
}
}
}
}
给定这样的配置(您需要将程序集名称设置为正确的名称):
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="false">
<appender name="HeaderAppender"
type="MyAssembly.log4net.Header.Example.HeaderAppender,MyAssembly">
<file value="c:\temp\Test.log"/>
<layout
type="MyAssembly.log4net.Header.Example.HeaderPatternLayout,MyAssembly">
<conversionPattern value="%message%newline" />
</layout>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<maximumFileSize value="5MB"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="-1"/>
<countDirection value="1"/>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="HeaderAppender" />
</root>
</log4net>
</configuration>
然后这是生成的日志文件,包含标题:
Static information
OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
Culture Info: en-GB
[Etc]
Messages:
Info Message
Debug Message
Etc