I am trying to integrate SeriLog into a project so that I can utilize structured logging. I am trying to put the files at a given path but the log files are not being made in the path I am giving. Instead they are being made in a different location
SeriLog config in my Program.cs :
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.MinimumLevel.Warning()
.CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
My appsettings.json:
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console"],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Error",
"System": "Debug"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:yyyy/MM/dd HH:mm:ss} {Level:u10}] {Message:lj} {NewLine}{Exception}{NewLine}",
"theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console"
}
},
{
"Name": "File",
"Args": {
"path": "Logs\\RestApiLog.log",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
"rollOnFileSizeLimit": true,
"fileSizeLimitBytes": 4194304,
"retainedFileCountLimit": 15,
"rollingInterval": "Minute"
}
}
]
}
My appsetting.Development.json:
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Error",
"System": "Debug"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:yyyy/MM/dd HH:mm:ss} {Level:u10}] {Message:lj} {NewLine}{Exception}{NewLine}",
"theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console"
}
},
{
"Name": "File",
"Args": {
"path": "E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
"rollOnFileSizeLimit": true,
"fileSizeLimitBytes": 4194304,
"retainedFileCountLimit": 15,
"rollingInterval": "Minute"
}
}
]
}
I have also implemented a ExceptionHandlingMiddleWare, I am attaching the code to it below:
public class ExceptionHandlingMiddleware
{
public RequestDelegate requestDelegate;
private readonly ILogger<ExceptionHandlingMiddleware> logger;
public ExceptionHandlingMiddleware(RequestDelegate requestDelegate, ILogger<ExceptionHandlingMiddleware> logger)
{
this.requestDelegate = requestDelegate;
this.logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await requestDelegate(context);
}
catch (Exception ex)
{
await HandleException(context, ex);
}
}
private Task HandleException(HttpContext context, Exception ex)
{
logger.LogError(ex.ToString());
var errorMessageObject = new { Message = ex.Message, Code = "system_error" };
var errorMessage = JsonConvert.SerializeObject(errorMessageObject);
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(errorMessage);
}
}
I have also added this line to progam.cs so that I can use this middleware:
app.UseMiddleware(typeof(ExceptionHandlingMiddleware));
I am also attaching an image so that you can see where the files should be created and where they are actually being created: [![The files are not being created in the log folder]
(https://i.sstatic.net/UTfwR.png)](https://i.sstatic.net/UTfwR.png)
What I immediately notice is that your path has a "logical" error.
You forgot to close your path at "E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs"
, it should look like "E:\\OneDrive - Octopus Digital\\OC_API\\OmniConnectAPI\\Logs\\"
.
You can see this perfectly in your files that were created, at the very beginning it says "Logs"
, the program thinks "\\Logs"
is the beginning of a file and not a folder.