Dispenser/DispenserCore/Configures/LogConfiguration.cs

80 lines
2.8 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DispenserCommon.LogUtils;
using DispenserCore.Service;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Exceptions;
namespace DispenserCommon.LogConfig;
/// <summary>
/// 日志配置类
/// </summary>
public class LogConfiguration
{
private static LogParamsService _logParamsService = new();
/// <summary>
/// 获取日志配置对象
/// </summary>
/// <returns></returns>
public static Logger GetLogger()
{
var logParams = _logParamsService.GetLogParams();
// 日志输出目录
var basePath = logParams!.Path ?? AppDomain.CurrentDomain.BaseDirectory;
// 适配最小日志级别
Enum.TryParse(logParams.Level, true, out LogEventLevel miniLevel);
return new LoggerConfiguration()
#if DEBUG
// 测试环境的话输出debug级别
.MinimumLevel.Debug()
#else
// 其他环境输出info 级别
.MinimumLevel.Information()
#endif
.MinimumLevel.Override("Microsoft", miniLevel)
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.Logger(
l =>
l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
.WriteTo.File(
Path.Combine(basePath, "logs", "debug", "debug-.log"),
rollingInterval: RollingInterval.Hour,
retainedFileCountLimit: 24
)
)
.WriteTo.Logger(
l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)
.WriteTo.File(
Path.Combine(basePath, "logs", "info", "info-.log"),
rollingInterval: RollingInterval.Hour,
retainedFileCountLimit: 72
)
)
.WriteTo.Logger(
l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning)
.WriteTo.File(
Path.Combine(basePath, "logs", "warning", "warning-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30
)
)
.WriteTo.Logger(
l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.File(
Path.Combine(basePath, "logs", "error", "error-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 90
)
)
// 测试环境同步输出到控制台
.WriteTo.Console()
.WriteTo.Sink(new DispenserLogSink())
.CreateLogger();
}
}