文章速览
- 概要
- 具体实施
- 创建Log系统
- 动态修改日志等级
坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~
概要
方便后期对软件进行维护,需要在一些关键处添加log日志输出,但时间长了之后会比较占用磁盘的内存;由于Log定义了不同的等级,因此可以根据等级来控制Log的具体磁盘写入。
主要通过【Serilog.Core.LoggingLevelSwitch】来控制日志的输出,前提是日志写入也是用该命名空间下的ILog进行写入。
具体实施
创建Log系统
/// <summary>/// 用来改变系统Log的输出日志等级/// </summary>public LoggingLevelSwitch LogLevelSwitch { get; private set; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Verbose);/// <summary>/// 创建日志系统,记录系统中发生的事件./// </summary>private ILogger buildLogService(){var basepath = "存储的路径";//使用系统的Log开关来控制LogLevelSwitch类var levelSwitcher = LogLevelSwitch;Log.Logger = new LoggerConfiguration()//控制最小输出日志.MinimumLevel.ControlledBy(levelSwitcher).WriteTo.Logger(lc => lc//此处的Fatal和Error写在一个文件中.Filter.ByIncludingOnly(v => v.Level == Serilog.Events.LogEventLevel.Error || v.Level == Serilog.Events.LogEventLevel.Fatal).WriteTo.File(Path.Combine(basepath, "error-.txt"),rollingInterval: RollingInterval.Day,rollOnFileSizeLimit: true,encoding: System.Text.Encoding.UTF8,retainedFileCountLimit: 10,fileSizeLimitBytes: 1024 * 1024)).WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(v => v.Level == Serilog.Events.LogEventLevel.Information).WriteTo.File(Path.Combine(basepath, "info-.txt"),rollingInterval: RollingInterval.Day,rollOnFileSizeLimit: true,encoding: System.Text.Encoding.UTF8,retainedFileCountLimit: 10,fileSizeLimitBytes: 1024 * 1024)).WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(v => v.Level == Serilog.Events.LogEventLevel.Warning).WriteTo.File(Path.Combine(basepath, "warning-.txt"),rollingInterval: RollingInterval.Day,rollOnFileSizeLimit: true,encoding: System.Text.Encoding.UTF8,retainedFileCountLimit: 10,fileSizeLimitBytes: 1024 * 1024)).WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(v => v.Level == Serilog.Events.LogEventLevel.Debug).WriteTo.File(Path.Combine(basepath, "debug-.txt"),rollingInterval: RollingInterval.Day,rollOnFileSizeLimit: true,encoding: System.Text.Encoding.UTF8,retainedFileCountLimit: 10,fileSizeLimitBytes: 1024 * 1024)).WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(v => v.Level == Serilog.Events.LogEventLevel.Verbose).WriteTo.File(Path.Combine(basepath, "verbose-.txt"),rollingInterval: RollingInterval.Day,rollOnFileSizeLimit: true,encoding: System.Text.Encoding.UTF8,retainedFileCountLimit: 10,fileSizeLimitBytes: 1024 * 1024))//写入日志系统.WriteTo.MAStorageSink().CreateLogger();return Log.Logger;}
动态修改日志等级
/// <summary>/// 更新LogLevel设置./// </summary>/// <param name="logLevel"></param>public void ResetLoggingLevel(LogEventLevel logLevel){//直接修改其MinimumLevel 属性即可LogLevelSwitch.MinimumLevel = logLevel;AppConfig.LogLevel = logLevel.ToString();SaveAppConfig();}