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),深受啟發,才寫成的。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM