using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Compact;
namespace Dpz.Core.Infrastructure.Configuration;
public static class LogConfiguration
{
private static bool LogFilter(LogEvent logEvent)
{
if (logEvent.Properties.TryGetValue("RequestPath", out var requestPath))
{
var pathPrefix = new[]
{
"/runtask",
"/account",
"/notification",
"/app/notification"
};
if (requestPath is ScalarValue value)
{
var result = pathPrefix.Any(x =>
value.Value?.ToString()?.StartsWith(x, StringComparison.CurrentCultureIgnoreCase) ?? false);
return result;
}
}
return false;
}
public static void ConfigurationLog(
this IHostBuilder host,
LogSeq? logSeq,
Func<LogEvent, bool>? filter = null)
{
if (logSeq == null ||
string.IsNullOrEmpty(logSeq.ServerUri) ||
#if !DEBUG
string.IsNullOrEmpty(logSeq.ApiKey) ||
#endif
string.IsNullOrEmpty(logSeq.Program))
{
throw new ArgumentNullException(nameof(logSeq));
}
var levelSwitch = new LoggingLevelSwitch();
host.UseSerilog((context, services, cfg) => cfg
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
//.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
.MinimumLevel.Information()
.Enrich.WithProperty("Version", Assembly.GetEntryAssembly()?.GetName().Version?.ToString() ?? "")
.Enrich.WithProperty("Server", Environment.MachineName)
.Enrich.WithProperty("Program", logSeq.Program)
.Enrich.FromLogContext()
.WriteTo.Logger(lc =>
{
lc.WriteTo.File(
new CompactJsonFormatter(),
Path.Combine("logs", $"{DateTime.Now:yyyyMM}", ".json"),
rollingInterval: RollingInterval.Day,
fileSizeLimitBytes: 10240);
})
.WriteTo.Logger(lc => { lc.WriteTo.Async(x => x.Console()); })
.WriteTo.Logger(lc =>
{
filter ??= LogFilter;
var loggerConfiguration = lc.Filter.ByExcluding(filter);
if (string.IsNullOrEmpty(logSeq.ApiKey))
{
loggerConfiguration.WriteTo.Seq(logSeq.ServerUri, controlLevelSwitch: levelSwitch);
}
else
{
loggerConfiguration.WriteTo.Seq(logSeq.ServerUri, apiKey: logSeq.ApiKey, controlLevelSwitch: levelSwitch);
}
})
);
}
}