我需要使用 log4net 登录到多个目标(loggly、console、file(。对于日志,我需要登录JSON以获取一些元数据来查找日志。我正在通过像这样将元数据添加到动态消息对象(示例主题(来更改消息对象。
public void Info(string message)
{
log.Info(GetLogObject(message));
}
private object GetLogObject(string message, Exception ex = null)
{
dynamic obj = new ExpandoObject();
obj.message = message;
obj.exception = ex;
obj.subject = _configuration.SubjectId;
return obj;
}
应用配置
版<log4net>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="LogglyAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender>
<appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
<rootUrl value="https://logs-01.loggly.com/" />
<inputKey value="*" />
<tag value="AppTag" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs/rolling.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%newline" />
</layout>
</appender>
现在,控制台和文件追加程序将 JSON 记录如下:
2017-06-12 15:28:10,236 INFO - {[message, Will collect every 1 Hours, 0 Minutes and 0 Seconds], [exception, ], [subject, 11111111-1111-1111-1111-111111111111]}
2017-06-12 15:28:10,271 INFO - {[message, Collection Round started at 12.06.2017 13:28:10], [exception, ], [subject, 11111111-1111-1111-1111-111111111111]}
我希望这些追加器只是记录消息本身(obj.message(如下所示:
2017-06-12 15:28:10,236 INFO - Will collect every 1 Hours, 0 Minutes and 0 Seconds
2017-06-12 15:28:10,271 INFO - Collection Round started at 12.06.2017 11:17:29
我该怎么做?非常感谢:)
如果为消息对象创建自己的类型(而不是使用动态对象(,并重写 ToString()
方法,会发生什么情况?我怀疑,LogglyAppender
会渲染图形,而常规PatternLayout
会求助于ToString()
。我没有尝试过这个,只是一个提示。你也许可以对ExpandoObject
进行子类化,以免失去这种动态性。