【6月日新计划16】WPF入门-Prism中配置NLog
1. NLog
官網地址: nlog-project.org/
使用方法都在Getting started
1.1 Install
需要安装到NuGet的程序包
-
NLog
-
NLog.Config
安裝包自動產生一個Config文件
右鍵屬性,修改為永遠複製或者有更新時才複製,然後建置動作為Resource(相對路徑)/Content(絕對路徑)
如果沒有,則在根目錄手動創建一個NLog.config文件(xml文件)
<?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>
1.2 config detail
2. Register
2.1 Exception
ObservableCollection<WeatherDto01> weather001 = (ObservableCollection<WeatherDto01>)result;
foreach (var item in weather001)
{
try
{
int v = 1;
int v2 = 0;
int ftemp = v / v2;
logger.Info("Hello world");
System.Console.ReadKey();
}
catch (Exception ex)
{
logger.Error(ex, "Goodbye cruel world");
}
logger.Info("asdfsadfasdf");
logger.Debug("adfasdfasdf");
System.Diagnostics.Trace.WriteLine("---------查看結果:" + item.GetType().GetProperty("Main").GetValue(item, null));
}
2.2 Use
//創建logger
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
// 在方法中使用
logger.Info("asdfsadfasdf");
logger.Debug("adfasdfasdf");
2.3 Extension
在编写程序的过程中,很难保证程序不会因为异常而退出,这时就需要将异常信息打印出来,方便查找问题的所在,所以需要在App.xaml.cs 中的CreateShell方法中订阅一些异常事件,并将这些异常信息打印到日志中
//----App.xaml.cs-----
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
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}");
}
2.4 Close
NLog.LogManager.Shutdown();
3. Debug
3.1 BreakPoint
3.2 Console
勾選自動變數