我目前正在使用log4net作为我正在处理的应用程序。我已经设置了一个CsvRollingFileAppender但我想知道如何将它扩展到日志传递的参数。一个例子就是以下几点:
log.Info(string.format("{0} - {1} - {2} - {3}", value1, value2, value3, value4));
我的Appender的配置看起来像这样
<appender name="CsvRollingFileAppender" type="DataCalcuation.Classes.CsvHeaderOverride">
<threshold value="INFO" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs/" />
<datePattern value="'DataCaclulation'.MM.dd.yyyy'.csv'" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<header value="DateTime,Level,Location,Message " />
<conversionPattern value="%date{M/d/yyyy H:mm:ss.fff},%level,%location,%message%newline" />
</layout>
</appender>
我想将其设置为具有
标题 DateTime, Level, Location, PassedValue1, PassedValue2, .....
我偶然发现了以下几篇不同的文章,并想知道这是否是正确的方法,或者是否有更有效的方式
非常感谢任何见解
我想我必须做这样的事情 - Mapping message properties to CSV columns using log4net
答案:
正如我所承诺的那样,我用来实现我想要做的代码所有的功劳都归功于Steven Padfield,我用过的帖子
我创建了一个名为CsvLogEvent的类,其中包含我想在日志中捕获的项目
public class CsvLogEvent
{
public int Value1 {get; set;}
public string Value2 {get; set;}
public string Value3 {get; set;}
public int Value4 {get; set;}
}
然后我使用以下格式记录事件
private readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Info(new CsvLogEvent {
Value1 = 1,
Value2 = "Test",
Value3 = "Log Event",
Value4 = 0
});
要对属性格式化CSV输出,我必须创建一个类来处理新的Pattern
public class CsvPattern : PatternLayout
{
public override void Format(TextWriter writer, LoggingEvent loggingEvent)
{
if (loggingEvent.MessageObject != null)
{
PropertyInfo[] properties = loggingEvent.MessageObject.GetType().GetProperties();
foreach(PropertyInfo prop in properties)
{
object value = prop.GetValue(loggingEvent.MessageObject, null);
loggingEvent.Properties[prop.Name] = value;
}
}
base.Format(writer, loggingEvent);
}
}
然后最终在app.config文件中设置appender
<appender name="Test" type="DataCalcuation.Classes.CsvAppender">
<threshold value="INFO" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs/" />
<datePattern value="'DataCaclulation'.MM.dd.yyyy'.csv'" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<staticLogFileName value="false" />
<layout type="DataCalcuation.Classes.CsvPattern">
<header value="DateTime,Level,Location,Value1, Value2, Value3, Value4 " />
<conversionPattern value="%date{M/d/yyyy H:mm:ss.fff},%level,%location,%property{Value1},%property{Value2},%property{Value3},%property{Value4}%newline" />
</layout>
</appender>