Reputation: 1242
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
Reputation: 387
"path": "D:\\Log\\log.log"
your CreateHostBuilder
method, should include:
Host.CreateDefaultBuilder(args)
.UseSerilog()
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