How to create logfile for each API using Serilog in .Net Framework?

717 Views Asked by At

I have created .Net Web API project using 4.6.2 Framework. I am using Serilog within my application. As of now its a Static Class as below.

public static class Logger
{
    private static readonly ILogger _logger;

    static A1Logger()
    {
        _logger = new LoggerConfiguration()
            .WriteTo.File(("C:/logs/log-.txt"), rollingInterval: RollingInterval.Day)
            .CreateLogger();
    }

    public static void LogError(string error)
    {
        //_logger.ToJSON(error);
        _logger.Error(error);
    }

    public static void LogInformation(string info)
    {
        _logger.Information(info);
    }
}

It creates log file and also logs information. However I want to create Logfile for each API.

For example If I Hit http://localhost:52137/Controller/sessions It should create Sessions Logfile and should log inside that file and If I hit http://localhost:52137/Controller/Event API it should create Event Logfile and start logging inside it.

RollingInterval should be as above in my Static class. I checked a lot on google there are lot of example for .NetCore fir Serilogs but I couldn't see anything much on .NET Framework. I think I have to use Filter as per my research however I am not sure how can I configure it in .Net Framework. Also, I think Static class wont help me to create multiple log files. Also logfile operation should be asynchronous.

Thank you in advance for your help and If you need some more information about please let me know.

1

There are 1 best solutions below

3
On

I can't comment so I'll post here.

Take a look at this other question.

It shows you how to filter based on the request path, using serilog-expressions.

Essentially, add configuration to filter the logs by the path. In code:

Log.Logger = new LoggerConfiguration()
    .Filter.ByIncludingOnly("RequestPath like '/Event API%'")
    .WriteTo.File("path/to/file/Event API.log");

in JSON:

    "Filter": {
        "Name": "ByIncluding",
        "Args": {
          "expression": "RequestPath like '/Event API%'"
        }
    }
    "WriteTo": "File",
    "Path": "path/to/files/Event API.log"

You can do this for each application you expect to use this logging library.

You may also be able to build these paths and expressions dynamically, based on incoming requests, so that it creates the files if they don't exist, but I don't have experience doing this.