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}");
}