Prism中配置NLog

Prism中配置NLog

在这里简单记录一下NLog在WPF中如何配置并如何注册到Prism的容器中

1. 准备工作

安装三个NuGet程序包

  • Microsoft.Extensions.Logging.Abstraction
  • NLog.Config
  • NLog.Extensions.Logging

2. 配置NLog

安装好之后在解决方案中会出现一个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"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- File Target for all log messages with basic details -->
    <target xsi:type="File" name="allfile" fileName="${basedir}/Logs/allfile/wpf-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

    <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="${basedir}/Logs/ownFile/wpf-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Output hosting lifetime messages to console target for faster startup detection -->
    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />

    <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />

    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

3. 创建实例并注册到IOC容器中

private ILogger _logger;
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    var factory = new NLogLoggerFactory();
    _logger = factory.CreateLogger("NLog.config");
    containerRegistry.RegisterInstance<ILogger>(_logger);
}

注册为单例类型,整个App使用的是同一个实例

4. 获取及使用

日志实例通过构造函数注入获取

public MainViewModel(ILogger logger)
{
    this._logger = logger;
}
_logger.LogInformation($"测试日志");

5. 注意

在编写程序的过程中,很难保证程序不会因为异常而退出,这时就需要将异常信息打印出来,方便查找问题的所在,所以需要在App.xaml.cs 中的CreateShell方法中订阅一些异常事件,并将这些异常信息打印到日志中

protected override Window CreateShell()
{
    //ui线程未捕获的异常
    DispatcherUnhandledException += OnDispatcherUnhandledException;
    //Task线程未捕获的异常
    TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
    //多线程异常
    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
    return Container.Resolve<MainView>();
}

private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
    _logger.LogCritical($"{e.Exception.StackTrace},{e.Exception.Message}");
}

private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
    _logger.LogCritical($"{e.Exception.StackTrace},{e.Exception.Message}");
}

private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Exception ex = e.ExceptionObject as Exception;
    _logger.LogCritical($"{ex.StackTrace},{ex.Message}");
}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GeGe&YoYo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值