zoukankan      html  css  js  c++  java
  • Asp.net Core 将日志输出到文件

    Asp.net core 内置的日志组件是将日志输出到控制台中,想要将日志输出到文件中,一般使用第三方的日志组件:如NLog 等 网上关于使用第三方组件输出日志到文件的教程很多,在这里我就不班门弄斧了

    本文主要记录下,如何不借助第三方日志组件,将日志输出到文件的实现方式

    在Asp.net Core 中可以通过实现 ILogger, ILoggerProvider 这两个接口来创建自定义的日志提供器。

    首先新建类 CustomFileLogger 继承 ILogger,以下为主要代码,需要引用 using Microsoft.Extensions.Logging;:

    public class CustomFileLogger : ILogger
        {
    
            private readonly string _name;
            private readonly CustomFileLoggerConfiguration _config;
            private LogLevel _logLevel;
    
            public CustomFileLogger(string name, CustomFileLoggerConfiguration config)
            {
                _name = name;
                _config = config;
            }
    
            public IDisposable BeginScope<TState>(TState state)
            {
                return null;
            }
    
            public bool IsEnabled(LogLevel logLevel)
            {
                return logLevel == _config.LogLevel;
                //return _config.MinLevel < logLevel;
            }
    
            public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
            {
                if(!IsEnabled(logLevel))
                {
                    return;
                }
                _logLevel = logLevel;
                FileLog($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:fff")} - {logLevel.ToString()} - {_name} - {formatter(state, exception)}");
            }
    
            private async void FileLog(string strLog)
            {
                string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + _logLevel.ToString() + ".txt";
                string filePath = _config.LogPath + "\" + fileName;
                File.AppendAllText(filePath, strLog);
                await File.AppendAllTextAsync(filePath,strLog);
            }
        }

    代码解释:IsEnabled 方法判断当前要输出的日志级别是否和自定义日志提供器中配置的日志级别相等,等于才会输出到日志文件中

    其中 CustomFileLoggerConfiguration 这个对象,是自定义的日志配置类,在添加自定义的日志提供器时,通过读取appsettings.json 中的配置信息,进行灵活的配置

    主要代码如下:

    public class CustomFileLoggerConfiguration
     {
            public CustomFileLoggerConfiguration()
            {
                MinLevel = LogLevel.Debug;
            }
    
            public LogLevel LogLevel { get; set; }
    
            /// <summary>
            /// 输出日志的最低级别,低于这个级别的不做输出,默认为Debug
            /// </summary>
            public LogLevel MinLevel { get; set; }
    
            /// <summary>
            /// 日志文件路径
            /// </summary>
            public string LogPath { get; set; }
      }

    最最关键的自定义日志提供器,代码如下,需要引用 using Microsoft.Extensions.Logging;:

    public class CustomFileLoggerProvider : ILoggerProvider
        {
    
            private readonly CustomFileLoggerConfiguration _config;
    
            public CustomFileLoggerProvider(CustomFileLoggerConfiguration config)
            {
                this._config = config;
            }
    
            public ILogger CreateLogger(string categoryName)
            {
                return new CustomFileLogger(categoryName,_config);
            }
    
            public void Dispose()
            {
               
            }
        }

    其中 CreateLogger是ILoggerProvider接口中定义的方法,它是用来返回一个日志生成器的,在这里就是返回一个自定义的日志生成器

    最后 修改Startup.cs中的Configure方法

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                //添加自定义的日志提供器
                loggerFactory.AddProvider(new CustomFileLoggerProvider(new CustomFileLoggerConfiguration
                {
                    MinLevel = (LogLevel)Enum.Parse(typeof(LogLevel), Configuration["FileLogPath:MinLogLevel"]),
                    LogLevel = LogLevel.Information,
                    LogPath = env.ContentRootPath+ Configuration["FileLogPath:LogPath"]
                })) ;
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }

    代码解释:LogPath 日志文件输出路经,读取appsetting.json 中的配置

    本来想实现一个功能,低于日志提供器中输出日志的最低级别(MinLevel)的日志就不再输出到文件中,但是始终不起作用(继续研究中) ,以下为配置文件

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Information",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "FileLogPath": {
        "LogPath": "\Logs",
        "MinLogLevel": 0
      }
    }

    这篇博文主要是看了这篇大作(https://www.cnblogs.com/lwqlun/p/9683482.html),深受启发,才写成的。

    有任何不足的,请各位博友多多指教,非常感谢。

    我要一步一步往上爬 在最高点乘着叶片往前飞 任风吹干 流过的泪和汗 我要一步一步往上爬 等待阳光静静看着它的脸 小小的天有大大的梦想 我有属于我的天 任风吹干流过的泪和汗 总有一天我要属于我的天
  • 相关阅读:
    钉钉 LDAP
    OpenLDAP 密码策略与审计控制
    Active Directory LDAP DingDing
    Linux kill 命令 java
    Memory Analyzer 与 Java VM 版本支持问题
    java.lang.Thread.State
    稻盛和夫 活法 人生公式
    [领导力/管理]一句话说带团队
    把某个公司git项目迁移到gitee的步骤
    Protocol Buffers  |  Google Developers
  • 原文地址:https://www.cnblogs.com/MrALei/p/14985586.html
Copyright © 2011-2022 走看看