简体   繁体   中英

in ASP.NET core (.NET5) how can i write logs for each request on separate files? Using Serilog or other

I'm new to .NET and to webservice development, so i'm not exactly sure how to implement the requirement i have.

  • <\/li>
  • <\/li>
  • <\/li><\/ul>

    I've managed to install Serilog and it works for what i need, but not when i get concurrent requests. I'm also not exactly sure how simultaneous requests are handled in .NET (i have no thread specific code written so far), but as far as i can tell, when i change Global Logger file name, that object is shared across all threads so all of them write to the same file.

    I'm open to using something other than Serilog.

One way to have dynamic file names based on a specific context is by using the Serilog.Sinks.Map and then, via a middleware in the request pipeline, you can add a property to the log context that drives the file name to be used when writing to the log.

Examples of similar usage of Serilog.Sinks.Map to decide which file name to use at run-time:

The best solution that I found to this problem was using Serilog.Sinks.Map<\/a> . I configured my Logger something like this:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Map("Name", "Default", (name, wt) => {
        var fileName = name == "Default" ? "log" : $"{log-{name}}" 

        wt.File($"./{fileName}-.txt");
    }).CreateLogger();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM