Wpf使用NLog将日志输出到LogViewer

1 LogViewer

LogViewer是通过UDP传输的高性能实时log查看器。

具有一下特性:

  • 通过UDP读取日志
  • 通过文件导入日志
  • 导出日志到一个文件中
  • 排序、过滤(日志树,日志等级)和查找
  • 突出显示搜索文本
  • 从UPD接收日志时忽略IP地址列表
  • 多接收器支持
  • 多种颜色主题

项目地址:https://github.com/Styort/LogViewer

2 将NLog日志输出到LogViewer中

2.1 新建wpf项目并添加nlog

wpf项目采用Prism框架,项目名称:LogToLogViewerApp

2.2 添加nlog库及nlog.config文件

nlog库

复制代码
<PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.13" />

<?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"
      throwExceptions="true"
      internalLogFile="c:\temp\console-example-internal.log"
      internalLogLevel="Info">
	<targets async="true">
		<target name="log4view" xsi:type="NLogVIewer" address="udp://127.0.0.1:7071"/>
	</targets>
	<rules>
		<logger name="*" minlevel="Trace" writeTo="log4view"></logger>
	</rules>
</nlog>

将nlog.config文件设置成如果较新则复制。

需要的其他依赖包:

复制代码
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="DryIoc.Microsoft.DependencyInjection" Version="8.0.0-preview-02" />
2.3 在app.xaml.cs文件中依赖注入功能

重写CreateContainerExtension方法如下:

复制代码
protected override IContainerExtension CreateContainerExtension()
{
    var services = new ServiceCollection();
    services.AddLogging(builder =>
    {
        builder.ClearProviders();
        builder.SetMinimumLevel(LogLevel.Debug);
        builder.AddNLog();
    });
    var container = new DryIoc.Container(CreateContainerRules());
    var x = container.WithDependencyInjectionAdapter(services);

    return new DryIocContainerExtension(x.Container);
    //return base.CreateContainerExtension();
}

2.4 在mainwindowviewmodel中使用注入ilogger接口并输出日志

在构造函数中注入ilogger,添加一个Log方法用于日志的输出

复制代码
public MainWindowViewModel(ILogger<MainWindowViewModel> logger)
{
    _logger = logger;
}

[RelayCommand]
private void Log()
{
    _logger.LogTrace("Log Trace");
    _logger.LogDebug("Log Debug");
    _logger.LogInformation("Log Information");
    _logger.LogWarning("Log Warning");
    _logger.LogError("Log Error");
    _logger.LogCritical("Log Critical");
}

3 总结

使用LogViewer可以接收多个app端的日志输出,并可以根据需要选择显示的日志级别。有助于开发人员可以实时关注程序的运行流程。

相关推荐
小二·14 小时前
微服务架构设计与实践
微服务·架构·wpf
暖馒15 小时前
WPF-Prism学习入门步骤记录
学习·wpf
baivfhpwxf202316 小时前
雷赛(Leadshine)EtherCAT 数字 I/O 模块(如 EMC-E5064-8)的状态指示灯(I/O 状态)说明
c#·wpf
故渊at1 天前
第二板块:Android 四大组件标准化学理 | 第十二篇:四大组件全景总结与系统服务(System Server)架构
android·架构·wpf·四大组件·system service
伶俜662 天前
# [特殊字符] 零基础学 ArkUI 数据持久化(专题三):5 种存储方案深度对比
学习·华为·wpf·harmonyos
IT策士2 天前
Redis 从入门到精通:数据结构String 与键管理
数据结构·redis·wpf
AC赳赳老秦2 天前
技术文章素材收集自动化:用 OpenClaw 自动爬取行业资讯、技术热点、优质文章
运维·开发语言·python·自动化·wpf·deepseek·openclaw
加号32 天前
【WPF】 Storyboard 故事板动画设计深度解析
wpf
xiaoshuaishuai82 天前
C# Avalonia 依赖属性与WPF的区别
开发语言·c#·wpf
大G的笔记本2 天前
生产级 Spring Boot 网关简单实现方案
wpf