= = =

ASP.NET Core visual logging component (ASP.NET Core visual logging component) , wechat friends also asked whether grafting to WPF, webmaster tried this morning, it is ok!

ASP.NET Core Web API (ASP.NET Core Web API)

[Video placeholder]

Actual steps:

  1. Create a WPF application

  2. Add ASP.NET Core, Serilog support

  3. Use Serilog in WPF forms

  4. The end

The actual practice of this article begins

1. Create a WPF application

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

Add ASP.NET Core and Serilog support

2.1 Nuget Install the Nuget package

Microsoft. Extensions. Hosting to specify version, not higher than 2.2.0:

The Install Package - Microsoft. Extensions. Hosting - Version 2.2.0 Install - Package Serilog. AspNetCore Install Package LogDashboardCopy the code

2.2 Configuring Serilog and ASP.NET Core

Open the app.xaml.cs file and add the following code. Look closely, the following configuration and an article in the Program. The cs file configuration is same, main is to configure Serilog, remember the output log separator using | |.

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 z} | | {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(); }}}Copy the code

Add the startup. cs file 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(); }); }}}Copy the code

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

The Serilog and LogDashboard components are now installed and configured:

  1. The Logs directory in the program output directory has generated log files.

  2. You can also open the LogDashboard visual log panel by typing the link below.

    http://localhost:5000/logdashboard

3. Use Serilog in WPF forms

Mainwindow. xaml adds several buttons to simulate adding normal logs, adding exception logs, and opening the visual log panel page:

<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 using Serilog" Height = "250" Width = "350" > < the StackPanel Margin="20"> <Button Content=" open log panel "Width="100" Height="35" Click=" openlogboard_click "/> Width="100" Height="35" Margin="0 20" Click="AddInfoLog_Click"/> <Button Content=" Click="AddErrorLog_Click"/> </StackPanel> </Window>Copy the code

Mainwindow.xaml.cs does the above:

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 (" Logs recorded in the WPF form "); } private void AddInfoLog_Click(Object sender, RoutedEventArgs e) {MyLoger. } 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 }); }}}Copy the code

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

Completion of 4.

This article focuses on practice. If you are not familiar with ASP.NET Core, you are advised to check out Microsoft’s official documentation system. Without solving, Copy the code directly into the text.

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