Follow up: quickly build the log panel in Winform/WPF

Posted by lilleman on Fri, 04 Mar 2022 10:46:33 +0100

Following yesterday's document, ASP Net core visual log component( Reading articlesView video )After that, a friend left a message under the video, "can Winform client program use it?", A friend of wechat also asked whether it could be grafted on WPF. The webmaster tried it this morning. It's OK!

The principle is to host Winform or WPF application to ASP Net core web API, first let's take a small video to see the effect. If you want to turn the code directly down:

[video space occupation]

Practical steps:

  1. Create a WPF application
  2. Add ASP Net core and Serilog support
  3. Using Serilog in WPF forms
  4. end

This article begins with actual combat

1. Create a WPF application

Using VS 2019, create a WPF application project named WPFWithLogDashboard. This article is based on NET 6.

2. Add ASP Net core and Serilog support

2.1 Nuget installation related Nuget packages

Microsoft.Extensions.Hosting must specify the version, which cannot be higher than 2.2.0:

Install-Package Microsoft.Extensions.Hosting -Version 2.2.0
Install-Package Serilog.AspNetCore
Install-Package LogDashboard

2.2 configuring Serilog and ASP NET Core

Open app xaml. CS file, add the following code. Take a closer look at the following configuration and the previous article program The configuration in the CS file is almost the same. It is mainly to configure the Serilog. Remember to use the output log delimiter 𞓜.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using System;
using System.Windows;

namespace WPFWithLogDashboard
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		protected override void OnStartup(StartupEventArgs e)
		{
			base.OnStartup(e);

			#region Serilog configuration

			string logOutputTemplate = "{Timestamp:HH:mm:ss.fff zzz} || {Level} || {SourceContext:l} || {Message} || {Exception} ||end {NewLine}";
			Log.Logger = new LoggerConfiguration()
			  .MinimumLevel.Override("Default", LogEventLevel.Information)
			  .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
			  .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
			  .Enrich.FromLogContext()
			  .WriteTo.Console(theme: Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme.Code)
			  .WriteTo.File($"{AppContext.BaseDirectory}Logs/Dotnet9.log", rollingInterval: RollingInterval.Day, outputTemplate: logOutputTemplate)
			  .CreateLogger();

			#endregion

			Host.CreateDefaultBuilder(e.Args)
				.UseSerilog()
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup<Startup>();
				}).Build().RunAsync();
		}
	}
}

Add startup CS file, the code is as follows:

using LogDashboard;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Serilog;

namespace WPFWithLogDashboard
{
	public class Startup
	{
		private ILogger logger;
		public ILogger MyLoger
		{
			get
			{
				if (logger == null)
				{
					logger = Log.ForContext<Startup>();
				}
				return logger;
			}
		}

		public void ConfigureServices(IServiceCollection services)
		{
			MyLoger.Information("ConfigureServices");

			services.AddLogDashboard();
			services.AddControllers();
		}

		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
		{
			MyLoger.Information("Configure");

			app.UseLogDashboard();

			app.UseRouting();

			app.UseEndpoints(endpoints =>
			{
				endpoints.MapControllers();
			});
		}
	}
}

In this file, the main function is to add LogDashboard components and configure NET CORE Web API routing.

After completing the above code, the two components of Serilog and LogDashboard have been installed and configured:

  1. The Logs directory of the program output directory has generated log files.
  2. The browser can also open the LogDashboard visual log panel by entering the following link.
http://localhost:5000/logdashboard

3. Use Serilog in WPF form

Main formmainwindow Xaml adds several buttons to simulate adding normal log, adding exception log and opening the web page of visual log panel:

<Window x:Class="WPFWithLogDashboard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Windows Used in Serilog" Height="250" Width="350">
    <StackPanel Margin="20">
        <Button Content="Open the log panel" Width="100" Height="35" Click="OpenLogDashboard_Click"/>
        <Button Content="Add normal log" Width="100" Height="35" Margin="0 20" Click="AddInfoLog_Click"/>
        <Button Content="Add exception log" Width="100" Height="35" Click="AddErrorLog_Click"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs to complete the above functions:

using Serilog;
using System.Diagnostics;
using System.Windows;

namespace WPFWithLogDashboard
{
	public partial class MainWindow : Window
	{
		private ILogger logger;
		public ILogger MyLoger
		{
			get
			{
				if (logger == null)
				{
					logger = Log.ForContext<MainWindow>();
				}
				return logger;
			}
		}

		public MainWindow()
		{
			InitializeComponent();

			MyLoger.Information("WPF Log recorded in form");
		}
		private void AddInfoLog_Click(object sender, RoutedEventArgs e)
		{
			MyLoger.Information("Test add Info journal");

		}

		private void AddErrorLog_Click(object sender, RoutedEventArgs e)
		{
			MyLoger.Error("Test add exception log");
		}

		private void OpenLogDashboard_Click(object sender, RoutedEventArgs e)
		{
			OpenUrl("http://localhost:5000/logdashboard");
		}

		private void OpenUrl(string url)
		{
			Process.Start(new ProcessStartInfo("cmd", $"/c start {url}")
			{
				UseShellExecute = false,
				CreateNoWindow = true
			});
		}
	}
}

OK, the function has been completed. The project built in this paper based on WPF is also applicable to Winform project template.

4. Closure

This article focuses on practice, if you are interested in ASP Net core is not well understood. I suggest you check Microsoft's official document system for learning; Without understanding, you can Copy the code in the text directly.

Is this article useful to you? Remember to walk three times in a row.

Topics: ASP.NET