我尝试使用log4net以JSON格式记录一些值。
以下是我的log4net配置
<appender name="DataDeleteAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\\deltanetscratch\\splunk\\DataDelete" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Date" />
<datePattern value="'.'yyyyMMdd'.log'" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
<decorator type="log4net.Layout.Decorators.StandardTypesFlatDecorator, log4net.Ext.Json" />
<default />
<remove value="message" />
<remove value="appname" />
<remove value="ndc" />
<remove value="logger" />
<remove value="thread" />
<member value="M:messageobject" />
</layout>
</appender>
<logger name="DataDelete">
<level value="INFO"/>
<appender-ref ref="DataDeleteAppender"/>
</logger>
以下是我的c#代码
_Log.Info(new
{
EndTime = DateTime.Now,
IsClientConnected = HttpContext.Current.Response.IsClientConnected,
batchSize = BatchSize,
searchStartDate = StartDate,
searchEndDate = EndDate,
emails = Emails,
ActionType = "Queue Course",
RowsAffected = HttpContext.Current.Items[ROW_COUNTER] == null ? "0" : HttpContext.Current.Items[ROW_COUNTER].ToString()
});
以下是我的输出。在此处查看所有属性获取M.前缀。我想删除前缀并获取属性。
{
"date":"2017-05-26T15:34:24.7920436+05:30",
"level":"INFO",
"M.EndTime":"2017-05-26T15:34:24.7920436+05:30",
"M.IsClientConnected":true,
"M.batchSize":2,
"M.searchStartDate":"2000-04-30T00:00:00.0000000",
"M.searchEndDate":"2008-04-30T00:00:00.0000000",
"M.emails":"lec@intl.com",
"M.ActionType":"Queue Course",
"M.RowsAffected":"0"
}
我期待输出如下。
{
"date":"2017-05-26T15:34:24.7920436+05:30",
"level":"INFO",
"EndTime":"2017-05-26T15:34:24.7920436+05:30",
"IsClientConnected":true,
"batchSize":2,
"searchStartDate":"2000-04-30T00:00:00.0000000",
"searchEndDate":"2008-04-30T00:00:00.0000000",
"emails":"lec@intl.com",
"ActionType":"Queue Course",
"RowsAffected":"0"
}
请问您如何实现此输出?
答案 0 :(得分:0)
这应该是相当简单的。替换:
<decorator type="log4net.Layout.Decorators.StandardTypesFlatDecorator, log4net.Ext.Json" />
与
<decorator type="log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json" />
StandardTypesFlatDecorator
使对象图变平,将成员路径作为前缀添加。
使用StandardTypesDecorator
,您可以将您的messageobject嵌套在logevent对象中。
如果这还不够好,那么我建议两个选择:
1)实现自己的装饰器 - 查看StandardTypesDecorator的来源 - 您可以覆盖Standardize()
方法以将LogEvent成员与自定义对象成员合并。