Search code examples
serilog

Serilog ForContext not working as expected


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


Solution

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