無論是Nlog還是Serilog, 它們都提供了如何快速在各類應用程序當中的快速使用方法。
盡管,你現在無論是在WPF或者ASP.NET Core當中, 都可以使用ServiceCollection來做到着一點, 因為日志框架都提供了IServiceCollection的擴展。
但是, 如果現在你使用的是Prism 8.0的應用程序, Prism提供了多種容器的支持, 例如:DryIoc或者Unity, 這個時候我們如果現在這個基礎上實現依賴注入,
首先我們需要修改Prism當中創建容器的默認實現, 在其中將ServiceCollection追加到容器當中。
本文的示例主要以DryIoc容器為示例:
這里會主要用到幾個相關的依賴:
- Microsoft.Extensions.DependencyInjection;
- Microsoft.Extensions.Logging;
- DryIoc.Microsoft.DependencyInjection;
- NLog.Extensions.Logging;
為此, 需要添加一些相關的包,如下所示:
Nlog.Config: 主要配置Nlog的執行配置,規則
NLog.Extensions.Logging: 擴展方法, 用於注冊服務
在App.xaml.cs代碼,如下所示:
protected override IContainerExtension CreateContainerExtension()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(configure =>
{
configure.ClearProviders();
configure.SetMinimumLevel(LogLevel.Trace);
configure.AddNLog();
});
return new DryIocContainerExtension(new Container(CreateContainerRules())
.WithDependencyInjectionAdapter(serviceCollection));
}
窗口中,添加測試代碼:
public partial class MainWindow : Window
{
private readonly Logger<MainWindow> logger;
public MainWindow(Logger<MainWindow> logger)
{
InitializeComponent();
this.logger = logger;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
logger.LogDebug("Hello");
}
}
注意: 配置Nlog需要修改Nlog.Config配置文件生效,可參考Github文檔, 下面為測試配置:
<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">
<targets>
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="f" />
</rules>
</nlog>
最終輸出內容,如下所示:
2021-08-19 16:32:00.5558|0|DEBUG|wpflogapp.MainWindow|Hello
2021-08-19 16:32:00.7049|0|DEBUG|wpflogapp.MainWindow|Hello
2021-08-19 16:32:00.8828|0|DEBUG|wpflogapp.MainWindow|Hello
2021-08-19 16:32:01.0647|0|DEBUG|wpflogapp.MainWindow|Hello
2021-08-19 16:32:01.2608|0|DEBUG|wpflogapp.MainWindow|Hello
完整App.xaml.cs文件代碼如下:
public partial class App : PrismApplication
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{ }
protected override IContainerExtension CreateContainerExtension()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(configure =>
{
configure.ClearProviders();
configure.SetMinimumLevel(LogLevel.Trace);
configure.AddNLog();
});
return new DryIocContainerExtension(new Container(CreateContainerRules())
.WithDependencyInjectionAdapter(serviceCollection));
}
}