Home > Enterprise >  Serilog doesn't write to text file the log of console log in ASP.NET Core 6 minimal API
Serilog doesn't write to text file the log of console log in ASP.NET Core 6 minimal API

Time:08-29

For debugging, I would like to write all what happens in the ASP.NET service. How I will install it as service, I need to write it in a text file.

But in debugging, I can see the output in console and in the text file.

First, I configure the json settings:

"Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": { "path": "Logs/log.txt" }
      }
    ],

And the I use this code in the program.cs of the ASP.NET Core project:

var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
        .Build();

var miFicheroTextoLogger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();

miFicheroTextoLogger.Information("Prueba");

In the console, I can see this:

[17:39:22 INF] Prueba
trce: Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilder[2]
      Discovering gRPC methods for GestorOrdenadores.Service.Server.Grpc.GestorOrdenadoresService.
trce: Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilder[1]
      Added gRPC method 'SayHello' to service 'greet.Greeter'. Method type: Unary, HTTP method: POST, route pattern: '/greet.Greeter/SayHello'.
dbug: Microsoft.Extensions.Hosting.Internal.Host[1]
      Hosting starting
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://[::]:5001
dbug: Microsoft.AspNetCore.Hosting.Diagnostics[13]
      Loaded hosting startup assembly GestorOrdenadores.Service.Server.Host.AspCore
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\desarrollo\proyectos\GestorOrdenadores\GestorOrdenadores.Service.Server.Host.AspCore\bin\Debug\net6.0\
dbug: Microsoft.Extensions.Hosting.Internal.Host[2]
      Hosting started

But in my text file I only have:

2022-08-26 17:39:22.057  02:00 [INF] Prueba

In the text file only writes what I told to write with miFicheroTextoLogger.Information("Prueba"); but I would like to write all what ASP.NET Core tells too.

Thanks.

CodePudding user response:

This code is wrong. First, there's no reason to create another configuration instance. The host generated by the minimal API template already uses these configuration sources.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

As the docs explain the default configuration reads from

  • appSettings.json and appSettings.{environment}.json
  • Environment variables
  • The command line

Logging can be configured through the builder.Logger property. If you add the Serilog.AspNetCore package you can also use the UseSerilog() method through builder.Host :

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console()
    .ReadFrom.Configuration(ctx.Configuration));

In this example the logger is configured using both code and settings.

You can also add request logging by adding this after `Build():

app.UseSerilogRequestLogging();

Putting this together :

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, lc) => lc
        .WriteTo.Console()
        .ReadFrom.Configuration(ctx.Configuration));

var app = builder.Build();
app.UseSerilogRequestLogging();

app.MapGet("/", () => "Hello World!");

app.Run();

The Serilog .NET 6 Minimal API example projects shows how to add Serilog to a Minimal API project configure it. It also adds a fallback logger should the startup process fail

  • Related