Serilog logger not writing logs to appropriate logs

580 Views Asked by At

I am trying to write to separate log files depending on where the method is run.

I have the Serilog configured in my AppStartup class

 Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(builder.Build())
        .Enrich.FromLogContext()
        .WriteTo.Logger(lc => lc
            .Filter.ByIncludingOnly(Matching.FromSource("DataProcessing.DataManagers.HistoricalEquityDataManager"))
            .WriteTo.File(LogFileTemplate.HistoricalDataLogFileTemplate.Replace("{machineuser}", Environment.UserName)))
        .WriteTo.File(LogFileTemplate.TradeActivityLogFileTemplate.Replace("{machineuser}", Environment.UserName))
        .WriteTo.Seq("http://localhost:5341")
            .CreateBootstrapLogger();

When methods from the class DataProcessing.DataManagers.HistoricalEquityDataManager are run I want them to log to a different file (noted in the config builder).

The logs from those methods are still writing to the file in the file noted in this codeline. They ARE NOT being run from the filtered logger.

.WriteTo.File(LogFileTemplate.TradeActivityLogFileTemplate.Replace("{machineuser}", Environment.UserName))
1

There are 1 best solutions below

0
On

The Matching.FromSource() methods require that the SourceContext property be present in the log context. See the source code for Matching.cs.

Adding the SourceContext property is achieved by creating a "local" ILogger instance in the constructor for each class and logging to that local instance.

public class Foo 
{
    private readonly ILogger _logger;
    
    public Foo() 
    {
        _logger = Log.Logger.ForContext<Foo>();
    }

    public void SomeMethod() 
    {
         _logger.Information("Hello world");
    }
}