(WPF)Serilog 使用demo实例

Serilog 日志效果:

引入的Serilog库文件

实现代码

xaml 代码:

<Window x:Class="Wpf_demo_Serilog.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:Wpf_demo_Serilog"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="600">
    <Grid>
        <StackPanel Orientation="Horizontal" Height="50" Width="300">
            <Button Content="info log" Click="Button_Click" Margin="10"/>
            <Button Content="error log" Click="Button_Click_1" Margin="10"/>
            <Button Content="debug log" Click="Button_Click_2" Margin="10"/>
        </StackPanel>
    </Grid>
</Window>

xaml.cs 代码:

using System.Threading.Tasks;
using System.Windows;

namespace Wpf_demo_Serilog
{

    public partial class MainWindow : Window
    {
        // at the beginning of the class
        private static Serilog.ILogger Logger => Serilog.Log.ForContext<MainWindow>();

        

        public MainWindow()
        {
            InitializeComponent();           
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Logger.Information("Hello World!");
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Logger.Information("Hello World!");
            TestClass1 tc = new TestClass1();
            tc.TestLog();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Logger.Debug("Hello China!");
            Task.Run(() =>
            {
                Logger.Information("HI~!");
            });
        }
        
    }
}

cs 代码:

using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Wpf_demo_Serilog
{
    public class TestClass1
    {
        private static Serilog.ILogger Logger => Serilog.Log.ForContext<TestClass1>();

        public  void TestLog()
        {
            try
            {
                int[] numbers = { 1, 2, 3 };
                Console.WriteLine(numbers[9]); // 不存在会报错!
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }

        }
    }
}

using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace Wpf_demo_Serilog
{   

    public partial class App : Application
    {
        public App()
        {
            InitLog();
        }

        private void InitLog()
        {
            StackTrace trace = new StackTrace();
            //获取是哪个类来调用的
            string sourceClass = trace.GetFrame(1).GetMethod().DeclaringType.Name;
            //LoggingExtensions.WithClassName();
            // 创建全局静态实例
            Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .Enrich.WithThreadId()
                .Enrich.WithProcessId()                 
                //设置最低等级
                .MinimumLevel.Verbose()               
                //将事件发送到文件
                //{Message:lj}表示将消息序列化成json字符串,string类型除外(j表示json,l表示except for string literals)
                //{Level:u3}表示将日志等级的输出显示为3个大写字符,如DBG、INF、ERR等。{Level:w3}表示三个字符的小写,
                //{Properties:j}用来显示额外的上下文信息
                .WriteTo.File(@".\Log\Log.txt",             /*日志文件名*/
                    outputTemplate:                         /*设置输出格式,显示详细异常信息*/
                    @"{Timestamp:yyyy-MM-dd HH:mm-ss.fff }[{Level}] (ThreadId:{ThreadId} ProcessId:{ProcessId} Class:{SourceContext}) {Message:lj}{NewLine}{Exception}",
                    rollingInterval: RollingInterval.Day,   /*日志按日保存*/
                    rollOnFileSizeLimit: true,              /*限制单个文件的最大长度*/
                    encoding: Encoding.UTF8,                /*文件字符编码*/
                    retainedFileCountLimit: 10,             /*最大保存文件数*/
                    fileSizeLimitBytes: 10 * 1024)          /*最大单个文件长度*/
                .CreateLogger();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            this.Dispatcher.UnhandledExceptionFilter += Dispatcher_UnhandledExceptionFilter;
            this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;

            base.OnStartup(e);
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Log.Error("[App_DispatcherUnhandledException] " + e?.Exception);
            e.Handled = true;
        }

        private void Dispatcher_UnhandledExceptionFilter(object sender, DispatcherUnhandledExceptionFilterEventArgs e)
        {
            Log.Error("[Dispatcher_UnhandledExceptionFilter] " + e?.Exception);
        }

        private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Log.Error("[Dispatcher_UnhandledException] " + e?.Exception);
            e.Handled = true;
        }
    }
}
 

相关推荐

  1. LLaMA-2 下载&demo使用

    2023-12-16 05:22:01       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-16 05:22:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-16 05:22:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-16 05:22:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-16 05:22:01       20 阅读

热门阅读

  1. Ansible

    Ansible

    2023-12-16 05:22:01      27 阅读
  2. 【置顶】 本博博文汇总

    2023-12-16 05:22:01       35 阅读
  3. cfa一级考生复习经验分享系列(五)

    2023-12-16 05:22:01       40 阅读
  4. 《小聪明》

    2023-12-16 05:22:01       33 阅读