Search code examples
c#.netloggingpathserilog

How to avoid logs to be written on relative path in .NET


I am using Serilog to write logs , this is how my configuration looks like :

Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .Enrich.FromLogContext()
        .WriteTo.Async(c => c.File($"Logs/log-.txt", rollingInterval: RollingInterval.Day))
        .WriteTo.Async(c => c.Console())
        .CreateLogger();

Problem with this is this is writing logs in bin/debug/.net7/logs

But I want it to write logs in my folder named Logs in the project.

This approach works fine in API projects but when I tried to use it in my Unit Test project then it logs it in bin/debug/.net7/logs

How can I change it so it should write logs in the folder that I created in root of my Unit Test Project ?


Solution

  • You could check whether a debugger is attached (using the System.Diagnostics namespace):

    string logPath = Debugger.IsAttached
        ? @"..\..\..\Logs\log-.txt"
        : @"Logs\log-.txt";
    Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File(logPath, rollingInterval: RollingInterval.Day))
            .WriteTo.Async(c => c.Console())
            .CreateLogger();
    

    The 3 ..\ move up by the 3 folders corresponding to bin/debug/.net7.