Net Core WPF中使用 NLog记录日志

2021-11-06  乐帮网

nlog wpf

首先建一个WPF项目。这里是以.Net 5 下的WPF为例,使用的工具是VS 2019 ,同理适用于.Net Core 3 和 log4net 。只要稍稍做修改就能适用。本例使用的环境为.Net 5 + Nlog + VS 2019 + Windows 10 。

1、添加Nuget 包,分别添加 NLog和 NLog.Web.AspNetCore,本人使用的都是最新稳定版。可以通过图形界面或者命令行
Install-Package NLog -Version 4.7.12
Install-Package NLog.Web.AspNetCore -Version 4.14.0
Install-Package Microsoft.Extensions.Logging.Abstractions

2、添加nlog.config文件配置日志的输出格式 并把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"
      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}" />
    -->
    <!--Error保存至文件-->
    <target name="error_file" xsi:type="File" maxArchiveFiles="30"  encoding="utf-8"
            fileName="${basedir}/Logs/${date:yyyyMMdd}_Error.log"
            archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_Error.{#}.log"
            archiveDateFormat="yyyyMMdd"
            archiveAboveSize="104857600"
            archiveNumbering="Sequence"
            layout="${date:yyyy-MM-dd HH\:mm\:ss} ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace}" />
    <!--Trace保存至文件-->
    <target name="trace_file" xsi:type="File" maxArchiveFiles="30" encoding="utf-8"
            fileName="${basedir}/Logs/${date:yyyyMMdd}_${level}.log"
            archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_${level}.{#}.log"
            archiveDateFormat="yyyyMMdd"
            archiveAboveSize="104857600"
            archiveNumbering="Sequence"
            layout="${date:yyyy-MM-dd HH\:mm\:ss} ${uppercase:${level}}: ${message}" />
	  <target name="info_file" xsi:type="File" maxArchiveFiles="30" encoding="utf-8"
            fileName="${basedir}/Logs/${date:yyyyMMdd}_${level}.log"
            archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_${level}.{#}.log"
            archiveDateFormat="yyyyMMdd"
            archiveAboveSize="104857600"
            archiveNumbering="Sequence"
            layout="${date:yyyy-MM-dd HH\:mm\:ss} ${uppercase:${level}}: ${message}" />
  </targets>

  <rules>
    <!-- add your logging rules here -->
    <logger name="*" minlevel="Trace" maxlevel="Debug" writeTo="trace_file" />
    <logger name="*" minlevel="Info" maxlevel="Warn" writeTo="info_file" />
    <logger name="*" minlevel="Error" writeTo="error_file" />
    <!--
    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、修改项目中的App.xaml文件,去掉 StartupUri="MainWindow.xaml"

4、修改类 App.xaml.cs,如下:

 protected override void OnStartup(StartupEventArgs e)
        {
            var host = CreateHostBuilder().Build();
            var serviceProvider = host.Services;

            var mainWindow = serviceProvider.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }


        private IHostBuilder CreateHostBuilder() =>
        Host.CreateDefaultBuilder()
         .ConfigureLogging(logging =>
         {
             logging.ClearProviders();
         }).UseNLog().ConfigureServices((hostContext, services) =>
         {
             services.AddTransient(typeof(MainWindow));
         });

5、添加配置文件appsettings.json,在这里面我们可以配置日志的输出级别如下:

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

要注意这个默认级别的值 Default

6、日志在类中使用示例如下 :

//https://lebang2020.cn/details/211106pdryeqxy.html
public partial class MainWindow : Window
    {
        private readonly ILogger<MainWindow> _logger;

        public MainWindow(ILogger<MainWindow> logger)
        {
            _logger = logger;
            InitializeComponent();
            _logger.LogTrace("我只是测试Nlog Demo.");
        }

    }

7、最终的结果如下图:

nlog

提供源码下载:链接:https://pan.baidu.com/s/1yTPU7hoQmharBQv_m0IoAg 

参考链接:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5

公众号二维码

关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com

庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。

欧阳修

付款二维码

如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力