.NET Core中的NLog事件属性 [英] NLog EventProperties in .NET Core

查看:353
本文介绍了.NET Core中的NLog事件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ILogger<MyController>使用DI编写日志(请参见步骤6 )

I'm using ILogger<MyController> to write logs using DI (see step 6)

我还在使用 NLog EventProperties

我想将traceId自动添加到控制器中的所有日志中.

I want to add traceId to all my logs in my controller automatically.

这有效:

logger.Info("Some log. TraceId:{traceId}", 123);

但是,然后我需要更改所有日志命令(很多!),这很麻烦.

However, then I need to change all my log commands (a lot of them!), which is a pain.

如果我执行以下操作,则可能不安全:

If I do the following, it's not tread safe:

using NLog;
public class MyController : Controller
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    public MyConstructor(Apilog apilog)
    {
        Logger.SetProperty("traceid", apilog.TraceId);
    }
}

是否可以通过ILogger<MyController>使用SetProperty?

Is there some way to use SetProperty with ILogger<MyController>?

还是以某种快速且线程安全的方式将NLog与SetProperty结合使用的方式?

Or some way of using NLog with SetProperty in a fast and thread safe way?

非常感谢!

推荐答案

在线程之间共享记录器时,可以使用WithProperty来确保线程安全.

When you share loggers between threads, then you could use WithProperty to ensure thread safeness.

请注意,WithProperty/SetProperty仅在NLog的Logger上可用. (因此不是Microsoft.Extensions.Logging`的ILogger).见下文.

Please note that WithProperty/SetProperty is only available on the Logger of NLog. (so not ILogger of Microsoft.Extensions.Logging`). See below.

示例:

using NLog;
public class MyController : Controller
{
    private static readonly Logger BaseLogger = LogManager.GetCurrentClassLogger(); 

    private readonly Logger Logger; // non static because of traceid. 
    public MyConstructor(Apilog apilog)
    {        
        Logger = BaseLogger.WithProperty("traceid", apilog.TraceId);
    }
}

是否可以通过ILogger<MyController>使用SetProperty?

Is there some way to use SetProperty with ILogger<MyController>?

Microsoft.Extensions.Logging的ILogger接口上没有SetProperty,但是您可以这样做:

There is no SetProperty on the ILogger interface of Microsoft.Extensions.Logging, but you could do this:

using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("traceid", apilog.TraceId) }))
{
   _logger.LogDebug("Log message");
}

并在您的配置中使用:${mdlc:traceid}.在此处查看更多详细信息和选项

And use in your config: ${mdlc:traceid}. See more details and options here

这篇关于.NET Core中的NLog事件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆