1

I am trying to use Serilog (both console and file) in a .NET Core console application.

In my Main class I initialise my logger like this:

Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.File("log.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
                .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
                .CreateLogger();

With {SourceContext}.{Method} I would like to know which class and method I am logging from.

I would like to use this very logger with the same settings in my other classes. So e.g. I initialize the logger in one of them like this:

private readonly ILogger _log = Log.ForContext<MyClass>();

But I doubt if this is generating the log I want, since when I try to log an exception like this

Log.Error(ex.Message);

the log I get does not mention the class and method:

2018-11-08 09:24:51.647 +01:00 [Error] (.) String '11/01/2018 11:43:00' was not recognized as a valid DateTime.

It seems as if the error has occurred in the Main method. So:

  1. Do I have to initialize the entire logger settings for every class?
  2. Save logger settings in a file and read from that file?
  3. Is there something wrong with the way I am trying to log in my code?
disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • You could make a static singleton of the Log so you won't have to initialize it in every class. And for formatting you can check out [this](https://stackoverflow.com/questions/48268854/how-to-get-formatted-output-from-logevent/48272467#48272467) or [2nd option](https://stackoverflow.com/a/29501667/7324631) – H.Mikhaeljan Nov 08 '18 at 09:19
  • @H.Mikhaeljan is there a place to refer to for making the singleton? I found this which does not seem to work https://stackoverflow.com/questions/26470951/using-serilog-through-a-wrapper-class. – disasterkid Nov 08 '18 at 10:07

0 Answers0