Search code examples
c#asp.net-coreserilog

Serilog: How to log, log message with different "origins" to different files


I want to log Information - Fatal with Serilog in my ASP.NET Core Web Application, using .NET Core 3.0

I want to log this data in different files (which was already asked and answered but my case is a little different I think):

  • information.log => information about what the application did (only using the automatic logging of Serilog / Microsoft)
  • error.log => All errors / unhandled exceptions that happen
  • other_information.log => (don't really have a name for this one) information about the program BUT only log messages created by me

I just can't figure out how to distinguish between information logs from Microsoft and my own.

I have found a question / answer on how to disable logging from Serilog / Microsoft but doing so it deactivates it for all LogWriters, How to turn off the logging done by the ASP.NET core framework .

Then I found an answer to another question which maybe is exactly what I'm looking for, but I don't understand what happens so I prefer to not use it, because I don't like magic because if there is a problem, fixing it is a lot more time-consuming, Can I log to separate files using Serilog?.

I also found another question that looks similar: Serilog : Log to different files but I don't understand this one either.

So if one of those really is the solution to my Problem I would be grateful if someone could explain it to me.

This is the Logger Configuration that I have until now, all it does is log all Information in one file and all errors in the other one.

            using Serilog;
            using Serilog.Events;            

            ...

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .WriteTo.Console()
                .WriteTo.Logger(l => l
                    .Filter.ByIncludingOnly(e => e
                    .Level == LogEventLevel.Information)
                    .WriteTo.File(@"Logs\Info.log"))
                .WriteTo.Logger(l => l
                    .Filter.ByIncludingOnly(e => e
                    .Level == LogEventLevel.Error)
                    .WriteTo.File(@"Logs\Error.log"))
                .CreateLogger();

And as I said, this works just fine to log all the information in one file and all the Errors in the other, but I don't know how to continue.

EDIT: I found the configurations I have at the moment from an answer to this question: Serilog - multiple log files‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌


Solution

  • I believe you just need to filter your log based on the property SourceContext, which is explained here: Filter Serilog logs to different sinks depending on context source?