Reputation: 89
I have a ASP .NET Core 3.1 web API and I'm trying to use Serilog, but for some reason any logs I create inside of my controllers don't log anything. Logging works when I log from the Startup class or through Middleware like UseSerilogRequestLogging().
My Program class:
public class Program
{
public static IConfiguration _configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(_configuration)
.Enrich.WithMachineName()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Application Starting.");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "The Application failed to start.");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
My controller:
private readonly IJobServiceRepository _jobServiceRepository;
private readonly ILogger _logger;
/// <summary>
/// Constructor for this API controller
/// </summary>
public JobsController(IJobServiceRepository jobServiceRepository, ILogger<JobsController> logger)
{
_jobServiceRepository = jobServiceRepository ??
throw new ArgumentNullException(nameof(jobServiceRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
_logger.LogInformation("TEST");
}
My appsettings.json:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
}
},
"AllowedHosts": "*"
}
What could be wrong?
Upvotes: 1
Views: 1829
Reputation: 1
I think in your controller class, where you are creating a logger instance in the second line, i.e
private readonly ILogger _logger
replace ILogger
with ILogger<"Your controller name">
, which is JobsController
in your case.
Upvotes: 0
Reputation: 1073
Everything looks good in Program.cs
class.
In Program.cs
you configure Serilog and use it Log.Information("Application Starting.");
- as a result it works
You can also use it in JobsController
Log.Information("Message");
Upvotes: 1