1

I have a .Net Worker Service app which has multiple threads. I want to log each thread into separate file to make it easier to read the logs. Any ideas to implement this?

2
  • Personally, id just sink to a proper log aggregator like SEQ or anything else. Structure your logs the way you want, and never worry about files again unless its backup Commented Aug 30, 2021 at 22:50
  • Please provide enough code so others can better understand or reproduce the problem. Commented Sep 2, 2021 at 8:46

1 Answer 1

5

A common way of deciding which sink to write to at run-time is to use the Serilog.Sinks.Map:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Map(_ => Thread.CurrentThread.ManagedThreadId,
        (threadId, wt) => wt.File($"log-{threadId}.log"))
.CreateLogger();

Log.Information("Hello from the main thread");

var task1 = Task.Run(() => Log.Information("Hello from thread X"));
var task2 = Task.Run(() => Log.Information("Hello from thread Y"));

Task.WaitAll(task1, task2);

Log.CloseAndFlush();

You should consider limiting the number of open sinks when using this approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.