Banana Cake
Banana Cake

Reputation: 1242

ASP.NET Core - Serilog in default the logger

I want to use Serilog in my ASP.NET Core app to log to a file. I have installed package Serilog.AspNetCore (it has dependencies to the Serilog.Settings.Configuration and Serilog.Sinks.File, so I guess I don't need any other package).

My goal is to achieve logging in my controllers like this:

...
private ILogger _log;
public MyController(ILogger<MyController> logger)
{
   _log = logger;
}
...

public ActionResult<MyResponse> Foo([FromRoute] Guid fooGuid)
{
   _log.LogError("error test");
}

In my appsettings.json I have this configuration:

"Serilog": {
    "Using": [],
    "MinimumLevel": "Information",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "patch": "D:\\Log\\log.log"
        }
      }
    ],
    "Application": "Centralized logging application"
  },
  "AllowedHosts": "*"

and my Program.cs looks like this:

  public static void Main(string[] args)
    {
      CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
          .ConfigureLogging((context, logging) =>
          {
            logging.ClearProviders();
            logging.AddSerilog().AddConfiguration(context.Configuration);
          })
          .ConfigureWebHostDefaults(webBuilder =>
          {
            webBuilder.UseStartup<Startup>();
          });

I think the problem is in the Program.cs file. What is the most easy way how to achieve this kind of loging to the file? Thanks.

Upvotes: 0

Views: 2612

Answers (1)

Yaniv Amrami
Yaniv Amrami

Reputation: 387

  1. you have a typo on your appsettings.json. It should state "path": "D:\\Log\\log.log"
  2. your CreateHostBuilder method, should include:

    Host.CreateDefaultBuilder(args)
    .UseSerilog()
    
  3. your Main method should include

    // reading from appsettings.json the logging settings
    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();
    

Upvotes: 1

Related Questions