MireaBackend/Endpoint/Configuration/AppConfig/LoggerConfiguration.cs

80 lines
3.2 KiB
C#
Raw Normal View History

2024-06-01 10:50:38 +03:00
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Configuration.General;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using Serilog.Formatting.Compact;
using System.IO;
namespace Mirea.Api.Endpoint.Configuration.AppConfig;
public static class LoggerConfiguration
{
public static IHostBuilder AddCustomSerilog(this IHostBuilder hostBuilder)
{
hostBuilder.UseSerilog((context, _, configuration) =>
{
2024-06-01 11:10:42 +03:00
var generalConfig = context.Configuration.Get<GeneralConfig>()?.LogSettings;
2024-06-01 10:50:38 +03:00
configuration
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate:
"[{Level:u3}] [{Timestamp:dd.MM.yyyy HH:mm:ss}] {Message:lj}{NewLine}{Exception}");
2024-06-01 11:10:42 +03:00
if (generalConfig?.EnableLogToFile == true)
2024-06-01 10:50:38 +03:00
{
2024-06-01 11:10:42 +03:00
if (!string.IsNullOrEmpty(generalConfig.LogFilePath) && Directory.Exists(PathBuilder.Combine(generalConfig.LogFilePath)))
Directory.CreateDirectory(generalConfig.LogFilePath);
2024-06-01 10:50:38 +03:00
configuration.WriteTo.File(
new CompactJsonFormatter(),
PathBuilder.Combine(
2024-06-01 11:10:42 +03:00
generalConfig.LogFilePath!,
generalConfig.LogFileName + ".json"
2024-06-01 10:50:38 +03:00
),
LogEventLevel.Debug,
rollingInterval: RollingInterval.Day);
}
configuration
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Warning);
configuration.Filter.ByExcluding(Matching.WithProperty<string>("SourceContext", sc =>
sc.Contains("Microsoft.EntityFrameworkCore.Database.Command")));
});
return hostBuilder;
}
public static IApplicationBuilder UseCustomSerilog(this IApplicationBuilder app)
{
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = "Handled {RequestPath} in {Elapsed:0.0000} ms";
options.GetLevel = (_, elapsed, ex) => elapsed >= 2500 || ex != null
? LogEventLevel.Warning
: elapsed >= 1000
? LogEventLevel.Information
: LogEventLevel.Debug;
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("UserAgent", httpContext.Request.Headers.UserAgent);
diagnosticContext.Set("RemoteIPAddress", httpContext.Connection.RemoteIpAddress?.ToString());
};
});
return app;
}
}