为WPF框架Prism注册Nlog日志服务

发布时间 2023-08-18 11:33:09作者: WebEnh
这篇文章介绍了为WPF框架Prism注册Nlog日志服务的方法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
 

无论是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代码,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
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));
}

窗口中,添加测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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文档, 下面为测试配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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>

最终输出内容,如下所示:

1
2
3
4
5
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文件代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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));
    }
}

到此这篇关于为WPF框架Prism注册Nlog日志服务的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。