简体   繁体   中英

ASP.NET Core ILogger does not log to Trace unless a debugger is attached

I am having a weird situation where I cannot receive any Trace from ASP.NET Core ILogger<T> unless a debugger is attached (even if I am running in Debug configuration). First let me explain:

I need to write logs to files by date, and I previously wrote a simple custom TraceListener for that, so I think I can reuse it without writing new Log Provider:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                logging.AddTraceSource("IISLogCleaner");
                // I added below line to make sure I am not missing anything
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

In Startup.ConfigureServices() , I add the listener:

            var listener = new DailyTraceListener(folder);
            Trace.Listeners.Add(listener);

Now for the logging background task:

    ILogger<CleanupTask> logger;

    public CleanupTask(ILogger<CleanupTask> logger)
    {
        this.logger = logger;
    }

    // ...

    async Task<int> WorkAsync(CancellationToken token)
    {
        System.Diagnostics.Debug.WriteLine("Start Working");
        this.logger.LogInformation("Start working");

        await Task.Delay(1000);

        this.logger.LogInformation("Work finished");
        return await Task.FromResult(10000);
    }

Here's the problem: with debugger attached, all the logs are written to log file. However, when I choose to Run without Debugging, even in Debug configuration, no file is created, no content is written, until I added the Debug.WriteLine calls, now only these lines get logged, but all the logger.LogInformation() are not recorded.

在此处输入图像描述

The Output window however, receive all the messages:

在此处输入图像描述

To be safe, I have deleted the appsettings.Development.json file and only appsettings.json remains. Here is the Log content:

"Logging": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
    }
},

Ages later, I know but I believe you are hitting this:

ASP.Net Core Logging and DebugView.exe

I spent 3 hours on this one today and feel your paint


TL;DR: Debugger.IsAttached is checked within Microsoft.Extensions.Logging.Debug.

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