Serilog ForContext not working as expected

喜欢而已 提交于 2019-12-11 04:06:48

问题


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.

I have few questions. please help

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) 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) 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>()

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


回答1:


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.

e.g.

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: 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.



来源:https://stackoverflow.com/questions/52712516/serilog-forcontext-not-working-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!