关于NLog在.NET CORE下如何进行日志的持久化及通过邮件发送日志

配置过程

  1. 安装NLog

    通过Nuget进行集成(NuGet Gallery | NLog.Web.AspNetCore 4.14.0)

    通过命令行安装 Install-Package NLog.Web.AspNetCore -Version 4.14.0

    通过可视化管理工具查找并安装 NLog.Web.AspNetCore

  2. 修改Program.cs

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((context, builder) =>
                {
                    // 适配原来的Log配置
                    builder.AddConfiguration(context.Configuration.GetSection("Logging"));
                    builder.AddConsole();
                    builder.AddDebug();
                    builder.AddEventSourceLogger();
                    // 以下关键配置
                    builder.AddNLogWeb();
                    builder.AddNLog();
                    // 关键配置结束
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://*:5000");
                    webBuilder.UseStartup<Startup>();
                });
    
  3. 配置Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ......
        
        // 在UseEndpoints之前增加如下增加对部分 Layout renderers 的支持
        app.Use(async (context, next) => {
            context.Request.EnableBuffering();
            await next();
        });
        
        ......
    }
    
  4. 增加NLog.config

    注意此文件配置为复制到输出目录

    每一项的配置可以参考下方的NLog配置项

    <?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"
          throwConfigExceptions="true">
    
        <targets>
            <!-- 文件持久化 -->
            <target name="f1" xsi:type="File"
                    layout="PROJECT:${iis-site-name}${newline}
    REQUEST:${newline}
    ${aspnet-request-method} ${aspnet-request-url}${newline}
    QUERYSTRING:${newline}
    ${aspnet-request-querystring}${newline}
    HEADERS:${newline}
    ${aspnet-request-headers}${newline}
    FORM:${newline}
    ${aspnet-request-form}${newline}
    POSTED-BODY:${newline}
    ${aspnet-request-posted-body}${newline}
    COOKIE:${newline}
    ${aspnet-request-cookie}${newline}${newline}
    ${longdate}|${uppercase:${level}}|${logger}${newline}${newline}
    ${message}${newline}${newline}
    ${exception:format=ToString}"
                    fileName="Logs\nlog-all-${shortdate}.log" />
            <!-- 邮件支持 -->
            <target xsi:type="Mail"
                    name="m1"
                    html="true"
                    replaceNewlineWithBrTagInHtml="true"
                    addNewLines="true"
                    subject="发送邮件主题:[测试项目][${level}]${message}"
                    to="接收人邮箱"
                    from="发送人邮箱"
                    body="PROJECT:${iis-site-name}${newline}
    REQUEST:${newline}
    ${aspnet-request-method} ${aspnet-request-url}${newline}
    QUERYSTRING:${newline}
    ${aspnet-request-querystring}${newline}
    HEADERS:${newline}
    ${aspnet-request-headers}${newline}
    FORM:${newline}
    ${aspnet-request-form}${newline}
    POSTED-BODY:${newline}
    ${aspnet-request-posted-body}${newline}
    COOKIE:${newline}
    ${aspnet-request-cookie}${newline}${newline}
    ${longdate}|${uppercase:${level}}|${logger}${newline}${newline}
    ${message}${newline}${newline}
    ${exception:format=ToString}"
                    smtpUserName="发送人账号"
                    enableSsl="true"
                    smtpPassword="发送人密码"
                    smtpAuthentication="Basic"
                    smtpServer="发送邮箱的smtp"
                    smtpPort="发送邮箱的smtp端口" />
    
        </targets>
    
        <rules>
            <logger name="*" minlevel="Error" writeTo="f1" />
            <logger name="*" minlevel="Error" maxlevel="Error" writeTo="m1" />
        </rules>
    </nlog>
    

相关资源

NLog官网:NLog (nlog-project.org)

NLog配置项:Config | NLog (nlog-project.org)

上一篇:可用的nlog配置


下一篇:NLog使用