Serilog ForContext 未按预期工作 [英] Serilog ForContext not working as expected

查看:130
本文介绍了Serilog ForContext 未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 serilog &在我的项目(MVC/web api 等)中使用 Autofac(DI)的 SEQ.虽然它工作正常但不确定这是正确的方法.

I am using serilog & SEQ with Autofac (DI) in my project (MVC/ web api etc). Although it's working fine but not sure it's the right way.

我有几个问题.请帮忙

Q1) 如何让 LoggerConfiguration 通过 Web.config(appsetting)如 Verbose/Debug 等进行管理

Q1) How can I make LoggerConfiguration is manage via Web.config (appsetting) such as Verbose/Debug etc.

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .Enrich.FromLogContext()                    
    .WriteTo.Seq(serilogUrl)
    .CreateLogger();

Q2) 使用 Everymessage 我想写用户 ID.我在没有使用"语句的情况下使用了推送属性.看下面的代码

Q2) With Everymessage I would like to write userid. I have used push propery with out "using" statement. see below code

public partial class Repo : BaseRepo<db>
    {
        public Repo(ILogger logger) : base(logger)
        {
            var currentuser = GetUserName();
            LogContext.PushProperty("User Name", currentuser);        
            Logger.ForContext<Repo>();
        }
  public void somefunction()
  { 
    try{}
    catch(exception e){
          Logger.Error(e, "Message");
        }
  }
}

Q3) 在构造函数中,我使用了 Logger.ForContext() 假设这会将类名写入每条消息.但它不起作用.

Q3) In a constructor I have used Logger.ForContext() assuming this will write class name to each message. but it's not working.

   Logger.ForContext<Repo>()

注意:我没有使用asp.net core/.net core

Note: I am not using asp.net core/.Net core

推荐答案

ForContext 返回一个新的 ILogger 引用,该引用具有添加到记录器的上下文信息,因此您必须捕获该引用并将其用于记录.

The ForContext returns a new ILogger reference that has the context information being added to the logger, so you have to capture that reference and use that for logging.

例如

public class YourClass
{
    private readonly ILogger _log;

    public YourClass(ILogger log)
    {
        _log = log
            .ForContext<YourClass>()
            .ForContext("CurrentUserName", GetUserName());

        // ...
    }

    public void Somefunction()
    { 
        try
        {
            // ...
        }
        catch(exception ex)
        {
            _log.Error(ex, "Message...");
        }
    }
}

<小时>

ps:鉴于您使用的是 Autofac,您可能有兴趣使用 Autofac-Serilog 集成用于上下文记录器注入,而不是手动完成.


ps: Given that you're using Autofac, you might be interested in using the Autofac-Serilog integration for contextual logger injection, instead of doing it manually.

这篇关于Serilog ForContext 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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