阅读 73

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 state)
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return logLevel == _config.LogLevel;
            //return _config.MinLevel < logLevel;
        }

        public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Funcstring> 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; }

        /// 
        /// 输出日志的最低级别,低于这个级别的不做输出,默认为Debug
        /// 
        public LogLevel MinLevel { get; set; }

        /// 
        /// 日志文件路径
        /// 
        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),深受启发,才写成的。

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

原文:https://www.cnblogs.com/MrALei/p/14985586.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐