.net6 Logger搭建和使用


Logger

1.前言

 基础概念就as you know了,除了微软内置的logger外,.net core 还支持了多重第三方log工具,比如

 

本文只做内置logging和Nlog说明,前置是我之前学的,后者是我项目中使用的,废话不多说,开搞~

logger管理我了解的很少,只是正常使用的程度,优化的话,有一个LoggerMessage,没具体用过,这里就不谈了,

感兴趣的同学可以自己看看:高性能Logger

2.内置log

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

ps:.Net 6中CreateDefaultBuilder方法被隐藏了,所以我们在使用或者配置时 直接使用builder

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();

builder.Services.AddRazorPages();
....

或者这些写也可以~

var builder = WebApplication.CreateBuilder();
builder.Host.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddConsole();
});

添加到构造函数中使用。

public class AboutModel : PageModel
{
    private readonly ILogger _logger;

    public AboutModel(ILogger<AboutModel> logger)
    {
        _logger = logger;
    }
    public string ? Message { get; set; }

    public void OnGet()
    {
        Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
        _logger.LogInformation(Message);
    }
}

在创建ASP.NET Core Web应用程序时,会在appsettings.Development.json文件中自动添加以下配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

这里需要知道一个概念log信息是分等级的(LogLevel),参数范围是0-6

Trace = 0、Debug = 1、Information = 2、Warning = 3、Error = 4、Critical = 5 和 None = 6。

比如,当default配置为Information时,log将会记录Information及更高级别的信息,Information = 2、Warning = 3、Error = 4、Critical = 5 。

Microsolt.AspNetCore 代表系统信息。

{
  "Logging": {
    "LogLevel": { // No provider, LogLevel applies to all the enabled providers.
      "Default": "Error",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Warning"
    },
    "Debug": { // Debug provider.
      "LogLevel": {
        "Default": "Information" // Overrides preceding LogLevel:Default setting.
      }
    },
    "Console": {
      "IncludeScopes": true,
      "LogLevel": {
        "Microsoft.AspNetCore.Mvc.Razor.Internal": "Warning",
        "Microsoft.AspNetCore.Mvc.Razor.Razor": "Debug",
        "Microsoft.AspNetCore.Mvc.Razor": "Error",
        "Default": "Information"
      }
    },
    "EventSource": {
      "LogLevel": {
        "Microsoft": "Information"
      }
    },
    "EventLog": {
      "LogLevel": {
        "Microsoft": "Information"
      }
    },
    "AzureAppServicesFile": {
      "IncludeScopes": true,
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AzureAppServicesBlob": {
      "IncludeScopes": true,
      "LogLevel": {
        "Microsoft": "Information"
      }
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

以上为所有的默认的provider,可以显示的指定其显示规则,如果要禁止显示所有的log,指定为LogLevel.None即可。

3.Nlog

官网:https://github.com/nlog/nlog/wiki
1.添加Nuget包引用:NLog.Web.AspNetCore

2.添加nlog.confg配置文件,或者安装包nlog.confg

 

 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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>

3.在CreateHostBuilder 中添加使用Nlog ( ConfigureLogging)

var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); // NLog: Setup NLog for Dependency injection builder.Logging.ClearProviders(); builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); builder.Host.UseNLog(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();

4.在配置文件中appsettings.Development.json添加,与内置log格式一样

{
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

5.调用即可

using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into HomeController");
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Hello, this is the index!");
        return View();
    }
}

 实战配置文件

<?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">
  <variable name="logLevel" value="${level:uppercase=true}"/>
  <variable name="logDate" value="${date:format=yyyy-MM-dd HH\:mm\:ss,fffz}"/>
  <variable name="version" value="${assembly-version}"/>
  <variable name="logFolder" value="${basedir}/logs"/>
  <variable name="operator" value="${replace:searchFor=(\\.[\\w]+)+:replaceWith=:regex=true:inner=${logger}}"/>
  <variable name="logFile" value="${appdomain:format={1\}}-${operator}.log"/>
  <variable name="exceptionContent" value="${exception:format=tostring}"/>
  <targets>
    <!--<default-wrapper xsi:type="BufferingWrapper" bufferSize="100"/>-->
    <!-- log to file -->
    <target name="AllLog" xsi:type="File"
            header="|Level|DateTime|CorrelationId|Version|Thread|Class|Message|"
            layout="|${pad:padding=-5:inner=${logLevel}}|${logDate}|${mdlc:CorrelationId}|${version}|${threadid}|${logger:shortName=true}|${message} ${onexception:${exceptionContent}|"
            fileName="${logFolder}/${logFile}"
            maxArchiveFiles="20"
            archiveAboveSize="5242880"
            archiveFileName="${logFolder}/${logFile}.{#}"
            archiveNumbering="Rolling"
            keepFileOpen="false"
            encoding="utf-8" />
    <target name="ELKLog" xsi:type="File"
            layout="${elkmessage}"
            fileName="/logs/elklogs/${logFile}"
            maxArchiveFiles="20"
            archiveAboveSize="5242880"
            archiveFileName="${logFolder}/elklogs/${logFile}.{#}"
            archiveNumbering="Rolling"
            keepFileOpen="false"
            encoding="utf-8" />
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" maxlevel="Fatal" writeTo="AllLog" />
    <logger name="*" minlevel="Debug" maxlevel="Fatal" writeTo="ELKLog" />
  </rules>
</nlog>

  

Demo代码已同步到Github上:EFCore_Redis_logger.

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM