WPF MVVM框架------ Prism中配置NLog
日志在生成环境中是必不可少的调试记录工具,在这里简单记录一下NLog在wpf中如何配置并如何注册到Prism的容器中
准备工作
需要安装三个NuGet程序包
Microsoft.Extensions.Logging.Abstraction
NLog.Config
NLog.Extensions.Logging
配置NLog
安装好之后在解决方案中会出现一个NLog.config,日志输出的路径,内容、规则等都在这个文件中进行配置,右击属性,将修改为始终复制。
若解决方案中没有出现NLog.config这个文件,则需要自己手动创建一个
关于配置,可以看NLog github上的介绍 github: 配置文件 ·NLog/NLog Wiki ·GitHub
<?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>
创建实例并注册到IOC容器中
打开App.xaml.cs
private ILogger _logger; protected override void RegisterTypes(IContainerRegistry containerRegistry) { var factory = new NLogLoggerFactory(); _logger = factory.CreateLogger("NLog.config"); containerRegistry.RegisterInstance<ILogger>(_logger); }
这里要注册为单例类型,整个App使用的是同一个实例
获取及使用
日志实例通过构造函数注入获取,
public MainViewModel(ILogger logger) { this._logger = logger; }
使用
_logger.LogInformation($"测试日志");
注意;
在编写程序的过程中,很难保证程序不会因为异常而退出,这时就需要将异常信息打印出来,方便查找问题的所在,所以需要在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}"); }
总结:
- 安装三个NuGet程序包
- 配置NLog.config
- 创建日志实例,并注册到IOC容器中
分类:
WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律