0

I have a simple web API using asp.net 5. I've added a Trace Listener so that the ILogger outputs to a file when I add Debug. This works fine in testing (within VS2019) in both debug and release mode. But when I deploy it to IIS it outputs nothing. It does manage to create the logfile but never puts anything in it.

my appsettings.json is the same in dev as in Prod ... is there another file I need?

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

here is my abSoundAPI.runtimeconfig.json as well

{
  "runtimeOptions": {
    "tfm": "net5.0",
    "framework": {
      "name": "Microsoft.AspNetCore.App",
      "version": "5.0.0"
    },
    "configProperties": {
      "System.GC.Server": true,
      "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }

}

Here is my Program class:

public static void Main(string[] args)
    {
        TextWriterTraceListener fileOutListener = new("abSoundAPI.log", "fileOutListnener");
        Trace.Listeners.Add(fileOutListener);
        Trace.AutoFlush = true;

        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception e)
        {
            Trace.WriteLine($"Fatal Exception {e.Message}");
            throw new Exception("Failed to start!");
        }
        finally
        {
            //Trace.Flush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging((context, logging) =>
            {
                logging.ClearProviders(); // see comments in code F12 on the CreateHostBuilder above
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddDebug();
                logging.AddConsole();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
Steven
  • 181
  • 8
  • Why did you add the trace listener at all? The same log events will go to all providers, unless you use filtering. The default providers include Console, Debug and Event Log. If you want to log to a file, add a file provider. To troubleshoot startup you can redirect the Console (Standard Output) to a file [through the aspNetCore tag in web.config settings](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/logging-and-diagnostics?view=aspnetcore-5.0). – Panagiotis Kanavos Sep 17 '21 at 06:37
  • @PanagiotisKanavos, curious .. is there some new built-in provider that extends it further? according to the MS Docs Console, EventSource, EventLog & Debug are the only ones. and I added the listener so that the Debug provider would output to a file in addition to the debug console. I wasn't aware of web.config settings.. i'll give that a shot.. thank you! – Steven Sep 17 '21 at 13:03
  • @PanagiotisKanavos , So the web.config settings seem to work fine, but this isn't what I am looking for .. this seems to be more for debugging the whole app (startup) ... not normal production logging for warning/critical level events. but I did learn something! :) – Steven Sep 17 '21 at 13:27
  • But that's exactly what you asked - how to redirect Debug output to a file. That's not done in production, that's typically done only when a debugger is attached. `Debug` is never used for production logging for precisely this reason. In a Release build the `Debug` class won't even log anything – Panagiotis Kanavos Sep 17 '21 at 13:40
  • Is your *real* question how to log during startup? – Panagiotis Kanavos Sep 17 '21 at 13:42
  • My question is why does this code work in testing .. but not when I deploy it to IIS. I'm sure its a setting somewhere .. but so far I haven't found it. – Steven Sep 17 '21 at 13:53
  • In a Release compile the Debug output is disabled. It's meant for output during *debugging*. Your code doesn't log anything to a file right now. Only to the console. Add a proper File log provider if you want to log to a file. There are a lot of great logging libraries that integrate with ASP.NET Core, eg Serilog, NLog and more. – Panagiotis Kanavos Sep 17 '21 at 13:58
  • is this true even if I Define TRACE & DEBUG constants? DEBUG;TRACE DEBUG;TRACE – Steven Sep 17 '21 at 14:09
  • Again, why? What are you trying to do? Why do you insist on trying to use `Debug` in production? `if I Define TRACE & DEBUG constants` don't define `DEBUG`. It's disabled for a reason. The .NET runtime itself and most packages create a *lot* of output during debugging that would slow down an application in production. `DEBUG` does a lot more than control the Debugger output – Panagiotis Kanavos Sep 17 '21 at 14:10
  • I am trying to get the app to log to a file when deployed to IIS. (Without a 3rd party library) I am not trying to use debug in production, I am teaching myself ILogger .. and the asp.net core logging system. It works fine when I run the code on my dev box .. then that exact same code deployed to IIS .. doesn't work. – Steven Sep 17 '21 at 14:13
  • `Without a 3rd party library` you can't. That's it. You'll either have to write your own file provider or use one of the *excellent* libraries. How is your TraceListener going to handle rolling files? File limits? Delete old files? How does it handle *caching* so it doesn't have to write all the time to disk? There's a lot more to logging than appending a line to a text file – Panagiotis Kanavos Sep 17 '21 at 14:17
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/237214/discussion-between-steven-and-panagiotis-kanavos). – Steven Sep 17 '21 at 14:17
  • Besides, logging to a file is insufficient nowadays. Sooner or later you'll want to use something like Prometheus, Elastic or a database instead of having to parse logs over and over. You'll want to use a system with alerts in case of specific problems. All these things have their own logging providers that can be used easily with `Microsoft.Extensions.Loggin`, often using a few lines like `.UseSerilog(..)` or `UsePrometheus(..)` – Panagiotis Kanavos Sep 17 '21 at 14:19
  • If the real question is how to log to files, there are duplicates [like this one](https://stackoverflow.com/questions/40073743/how-to-log-to-a-file-without-using-third-party-logger-in-net-core). As the answers show, it's not that simple. The "simple" answer has severe concurrency and performance problems – Panagiotis Kanavos Sep 17 '21 at 14:57

1 Answers1

0

Have you checked if you have any environment specific file like appsettings.development.json? because set the asp.net application in iis, you should use appsettings.development.json instead of appsettings.json.

You should modify the appsettings.development.json as below:

{
 "Logging": {
   "LogLevel": {
     "Default": "Trace",
     "Microsoft": "Warning",
     "Microsoft.Hosting.Lifetime": "Information"
   }
 }
}
samwu
  • 3,857
  • 3
  • 11
  • 25
  • That's [simply wrong](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0#appsettingsjson-1). `appsettings.json` is always used. So is `appsettings.Production.json` if it exists, to override settings in production. Development and Staging are used [only if the DOTNET_ENVIRONMENT or ASPNETCORE_ENVIRONMENT](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-5.0#environments-1) environment variables are set, only to override settings. On a production server `appsettings.Development.json` will be ignored – Panagiotis Kanavos Sep 17 '21 at 06:29
  • @samwu ... thanks! the logging level and categories have no impact on the issue. I get log events added to the log file when testing in VS (Debug & Release mode). The issue is when I publish the app to the server. I've tried multiple ways of setting the log level in both the appsettings.json as well as the abSoundAPI.runtimeconfig.json .. nothing so far has had an impact. :/ – Steven Sep 17 '21 at 13:32