WPF Serilog

Install-Package Serilog;
Install-Package Microsoft.Extensions.DependencyInjection;
Install-Package Microsoft.Extensions.Hosting;
Install-Package Serilog.Sinks.Console;
Install-Package Serilog.Sinks.File;
Install-Package Serilog.Sinks.Seq; 
Install-Package Serilog.Sinks.ObservableCollection;
Install-package Microsoft.Extensions.DependencyInjection;
Install-Package Microsoft.Extensions.Logging;
Install-Package CommunityToolkit.mvvm;

 

 

//App.xaml
<Application x:Class="WpfApp23.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp23">
    <Application.Resources>
         
    </Application.Resources>
</Application>

//App.xaml.cs
using System.Configuration;
using System.Data;
using System.Windows;
using Serilog;
using Serilog.Events;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace WpfApp23
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private IHost? host;
        public static IServiceProvider? Services { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            //Configure Serilog
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .Enrich.WithProperty("App", "WpfApp23")
                .WriteTo.Console()
                .WriteTo.File("Logs/log_.txt",
                rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 7,
                shared: true)
                .CreateLogger();

            Log.Information("Starting application");


            //Setup host+di
            host=Host.CreateDefaultBuilder()
                .UseSerilog()
                .ConfigureServices((context, services) =>
                {
                    services.AddSingleton(services.BuildServiceProvider());
                    services.AddSingleton<MainWindow>();
                    services.AddSingleton<MainViewModel>();
                }).Build();

            //Global exception handlers
            AppDomain.CurrentDomain.UnhandledException += (s, args) =>
            {
                Log.Fatal(args.ExceptionObject as Exception, "AppDomain unhandled exception");
                Log.CloseAndFlush();
            };

            this.DispatcherUnhandledException += (s, args) =>
            {
                Log.Error(args.Exception, "Dispatcher unhandled exception");
            };

            TaskScheduler.UnobservedTaskException += (s, args) =>
            {
                Log.Error(args.Exception, "Ubobserved task exception.");
            };

            //start host
            host.Start();

            var mainWin = host.Services.GetRequiredService<MainWindow>();
            mainWin.Show();
                 
            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Log.Information("Shutting down");
            host?.StopAsync().GetAwaiter().GetResult();
            host?.Dispose();
            Log.CloseAndFlush();
            base.OnExit(e);
        }
    }

}


//MainWindow.xaml
<Window x:Class="WpfApp23.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp23"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>

    </Grid>
</Window>


//MainWindow.xaml.cs
using Microsoft.Extensions.Logging;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp23
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly MainViewModel vm;
        private readonly ILogger<MainWindow> logger;

        public MainWindow(MainViewModel vmValue,ILogger<MainWindow> loggerValue)
        {
            InitializeComponent();
            vm = vmValue;
            logger = loggerValue;
            DataContext = vm;
            logger.LogInformation("MainWindow constructed and DataContext set!");
        }
    }
}


//MainViewModel.cs
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace WpfApp23
{
    public partial class MainViewModel:ObservableObject
    {
        private readonly ILogger<MainViewModel> logger;
        private string _sampleText = "Hello Serilog + WPF";

        public MainViewModel(ILogger<MainViewModel> loggerValue)
        {
            logger= loggerValue;
            Serilog.Log.Logger.Information("MainViewModel created!");
        }
    }
}

 

 

 

 

2025-10-02 21:00:55.824 +08:00 [INF] Starting application
2025-10-02 21:00:55.992 +08:00 [DBG] Hosting starting
2025-10-02 21:00:56.006 +08:00 [INF] Application started. Press Ctrl+C to shut down.
2025-10-02 21:00:56.011 +08:00 [INF] Hosting environment: Production
2025-10-02 21:00:56.012 +08:00 [INF] Content root path: D:\C\WpfApp23\WpfApp23\bin\Debug\net10.0-windows
2025-10-02 21:00:56.012 +08:00 [DBG] Hosting started
2025-10-02 21:00:56.012 +08:00 [INF] MainViewModel created!
2025-10-02 21:00:56.119 +08:00 [INF] MainWindow constructed and DataContext set!
2025-10-02 21:00:58.901 +08:00 [INF] Shutting down
2025-10-02 21:00:58.902 +08:00 [DBG] Hosting stopping
2025-10-02 21:00:58.907 +08:00 [INF] Application is shutting down...
2025-10-02 21:00:58.909 +08:00 [DBG] Hosting stopped

 

posted @ 2025-10-02 21:01  FredGrit  阅读(6)  评论(0)    收藏  举报