Location>code7788 >text

Wpf using NLog to output logs to LogViewer

Popularity:621 ℃/2024-09-21 14:20:21

1 LogViewer

LogViewer is a high performance real-time log viewer over UDP.
It has the following characteristics:

  • Reading logs over UDP
  • Importing logs via files
  • Exporting logs to a file
  • Sorting, filtering (log trees, log hierarchies) and lookups
  • Highlight search text
  • Ignore IP address list when receiving logs from UPD
  • Multi-Receiver Support
  • Multiple Color Themes

Project Address:/Styort/LogViewer

2 Output NLog logs to LogViewer

2.1 New wpf project and add nlog

The wpf project uses the Prism framework, project name:LogToLogViewerApp

2.2 Adding nlog libraries and files

nlog library

<PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="" Version="5.3.13" />
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="/schemas/"
      xmlns:xsi="http:///2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="true"
      internalLogFile="c:\temp\"
      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>

Set the file to copy if newer.
Other dependency packages needed:

<PackageReference Include="" Version="8.3.2" />
<PackageReference Include="" Version="8.0.0-preview-02" />
2.3 Dependency injection in documents

Override the CreateContainerExtension method as follows:

protected override IContainerExtension CreateContainerExtension()
{
    var services = new ServiceCollection();
    (builder =>
    {
        ();
        ();
        ();
    });
    var container = new (CreateContainerRules());
    var x = (services);

    return new DryIocContainerExtension();
    //return ();
}

2.4 Using the injection ilogger interface in the mainwindowviewmodel and outputting logs
Inject ilogger into the constructor, add a Log method for logging out

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 Summary

LogViewer can receive log output from multiple apps, and you can select the level of logs to display as needed. It helps developers to keep an eye on the running process of the program in real time.