have serilog logs reference the code where the log originated

55 views Asked by At

For example right now I'm getting this log from serilog:

The query uses the 'First'/'FirstOrDefault' operator without 'OrderBy' and filter operators. This may lead to unpredictable results.

and this is it, no stacktrace, some File.cs and line number, nothing.

How do I make serilog write where this log has originated from (file, line number) ?

this is my current appsettings.json serilog configuration:

"Serilog": {
  "MinimumLevel": {
    "Default": "Information"
  },
  "WriteTo": [
    { "Name": "Console" },
    {
      "Name": "File",
      "Args": {
        "path": "./logs/log.json",
        "rollingInterval": "Day",
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
        "restrictedToMinimumLevel": "Warning"
      }
    }
  ]

in Program.cs I'm setting it up like this:

builder.Host.UseSerilog(
        (context, configuration) => configuration.ReadFrom.Configuration(context.Configuration));
1

There are 1 answers

1
Qiang Fu On

You could try following sample:

using Microsoft.Extensions.Configuration;

var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
Log.Logger= new LoggerConfiguration()
   .ReadFrom.Configuration(config)
   .CreateLogger();
try
{
    throw new Exception("test error");
}

catch (Exception ex)
{
    Log.Error( ex,"");
}
Console.ReadLine();

enter image description here