1. 程式人生 > 其它 >在.Net Core Web API中使用NLog元件

在.Net Core Web API中使用NLog元件

1、引用NLog元件

通過NuGet安裝NLog、NLog.Web.AspNetCore包。

2、NLog配置

在專案中新增NLog.config檔案,將其“生成操作”屬性設定為“內容”,“複製到輸出目錄”屬性設定為“如果較新則複製”,配置資訊參見注釋:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload
="true" keepVariablesOnReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="log/nlog.txt"> <!-- the targets to write to --> <targets async="true"> <!-- File Target for all log messages with basic details --> <!-- enableFileDelete: 是否允許刪除日誌檔案。其取值型別為Boolean,預設為true。 maxArchiveFiles: 儲存的最大存檔檔案數。其型別類Integer,預設為9個。 archiveNumbering: 存檔檔案的編號方式。 可選值: Rolling – 滾動式編號,即最新的日誌檔案編號為0,然後是1,… ,N。 Sequence – 序列式編號,即最大編號的日誌檔案為最新的日誌檔案。 archiveAboveSize: 存檔上限值。當日志文件大於此值是,將自動存檔。其型別為Long。 注意:在多程序併發記錄日誌的情況下,啟用該選項可能會大幅降低日誌記錄速度。 在單程序時,為了達到最佳效能,可以考慮設定ConcurrentWrites為false。 bufferSize: 日誌檔案快取區大小(單位:位元組)。其取值型別為Integer,預設值為32768(32KB)。 deleteOldFileOnStartUp: 啟動時,是否刪除舊的日誌檔案。其取值型別為Boolean,預設為false。 concurrentWriteAttemptDelay: 在再次嘗試將日誌寫入檔案之前延遲的毫秒數。其取值型別為Integer,預設值為1。 備註:實際的延遲時間,是一個介於0到指定引數值之間的隨機整數,且在每次嘗試失敗之後,都會將此引數加倍。 假使此引數值為10,則第一次重試寫入的延遲時間(毫秒數)在
0-10之間的一個隨機數, 第二次重試時為0-20之間的一個隨機數,第三次重試時為0-40之間的一個隨機數, 第四次重試時為0-80之間的一個隨機數等等,以此類推。 keepFileOpen: 是否保持日誌檔案處於開啟狀態,以代替其在每次日誌寫事件發生時頻繁開啟和關閉。 其取值型別為Boolean,預設值為false。 備註:設定此屬性為true,有助於提高效能。 openFileCacheTimeout: 檔案保持開啟狀態的最大時間秒數。如果這個數字為負數,則在一定不活動時間後, 檔案不會自動關閉。其取值型別為Integer,預設值為
-1。(即默 認狀態下檔案始終處於開啟狀態以備寫入。) autoFlush: 在每次日誌資訊後,是否自動重新整理檔案快取區。其取值型別為Boolean,預設值為true。 createDirs: 是否允許自動建立(不存在的)目錄。其取值型別為Boolean,預設為true。 encoding: 檔案編碼方式。 archiveFileName: 存檔檔名稱。允許使用Layout。 --> <target xsi:type="File" name="allfile" fileName="${basedir}/logs/log.txt" enableFileDelete="true" maxArchiveFiles="20" concurrentWrites="true" archiveNumbering="Sequence" archiveAboveSize="2097152" bufferSize="327680" deleteOldFileOnStartup="false" concurrentWriteAttemptDelay="10" keepFileOpen="true" openFileCacheTimeout="30" autoFlush="false" openFileFlushTimeout="30" createDirs="true" encoding="utf-8" enableArchiveFileCompression="true" archiveFileName="${basedir}/archivelogs/log${date:format=yyyy\-MM\-dd_HH\-mm\-ss}.zip" layout="[${counter}] ${longdate} [${level}] [${processid}] [${processname}] ${message} ${newline} ${stacktrace}"/> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile"/> </rules> </nlog>

3、注入NLog元件

在注入NLog元件之前要先對其進行配置,然後通過IHostBuilder介面注入NLog元件。

修改Program.cs如下:

public class Program
{
    public static void Main(string[] args)
    {
        var configFileName = Path.Combine("Config", "NLog.config");
        var logger = NLogBuilder.ConfigureNLog(configFileName).GetCurrentClassLogger();
        try
        {
            logger.Debug("Program startup.");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            logger.Debug("Program shutdown.");
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .UseNLog(); // NLog: Setup NLog for Dependency injection
}

4、使用NLog元件

正常使用ILogger介面注入即可,不需要額外程式碼修改。

[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
}