我有一个.NET Core 3.1 Web服务,并使用NLog 4.7.0进行日志记录。我目前正在使用文件日志记录和filebeat将消息从日志文件发送到ELK。
我想为我的FileTarget
创建一个包装目标。实际目的是将单个Web请求的所有日志合并为一条日志消息,但这可能不重要。
我想从NLog.Targets.Wrappers.WrapperTargetBase
继承,但是Write(LogEventInfo logEvent)
方法是密封的。这是否意味着我只能对WrapperTargets使用异步日志记录?
这会影响我设置日志记录配置的方式吗?请注意,我使用的是配置文件,而不是配置API。
我现有的FileTarget
如下:
"appFile": {
"type": "File",
"fileName": "c:\\wwwlogs\\MyWebApp\\Combined.log",
"archiveFileName": "c:\\wwwlogs\\MyWebApp.Web\\archives\\Combined.{#}.log",
"archiveEvery": "Day",
"archiveNumbering": "Rolling",
"maxArchiveFiles": "7",
"layout": "${longdate}|${aspnet-request-ip}|${aspnet-TraceIdentifier}|${aspnet-user-identity}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
}```
答案 0 :(得分:1)
您有一些选择:
在所有情况下,您都需要在类中使用该属性:
[Target("MyWrapper", IsWrapper = true)]
从WrapperTargetBase继承时,您的目标可能是异步的,但也可以同步。您需要更多代码来处理它。
protected override void Write(AsyncLogEventInfo logEvent)
WrappedTarget.WriteAsyncLogEvent(logEvent);
为目标在不使用WriteAsyncLogEvent
时,请不要致电logEvent.Continuation
(带异常或空值)
写作事件分组
protected override void Write(IList<AsyncLogEventInfo> logEvents)
AsyncHelpers
另一个选择是从目标Inherit
。这是更简单的方法,但是开箱即用不适用于异步。
因为您有[Target("MyWrapper", IsWrapper = true)]
,所以可以使用。您在课堂上需要这个:
/// <summary>
/// Gets or sets the target that is wrapped by this target.
/// </summary>
[RequiredParameter]
public Target WrappedTarget { get; set; }