WPF 手撸插件 七 日志记录(二)

1、本文使用Serilog进行记录日志,目前想只用log4net进行日志记录,但是Serilog有想学习一下,所有这里使用控制台项目来学习一下Serilog。我使用的还是.Net Framework 4.5.

2、NuGet 安装Serilog 2.12.0、Serilog.Sinks.Console 4.1.0,如下图。

3、代码示例。

3.1、将信息输入到控制台,代码如下。

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
            logger.Information("信息日志");
            Console.ReadKey();
        }
    }
}

运行效果如下图。

3.2、将日志信息输出到文件,添加NuGet Serilog.Sinks.File 4.1.0,如下图。

示例代码如下。其中自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration()
                .WriteTo.Console(theme:AnsiConsoleTheme.Code)
                .WriteTo.File(@"Log/log.txt",rollingInterval:RollingInterval.Day,rollOnFileSizeLimit:true)//自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期
                .CreateLogger();
            logger.Information("信息日志");
            Console.ReadKey();
        }
    }
}

效果如下图。

3.3、将日志以json数据形式打印到控制台和文件中,效果如下图。

创建一个LogInfo类,代码如下。

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppSerilog
{
    public class LogInfo
    {
        public int Index { get; set; }

        public string Description { get; set; }
    }
}

Main函数代码如下。

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration()
                .WriteTo.Console(theme:AnsiConsoleTheme.Code)
                .WriteTo.File(@"Log/log.txt",rollingInterval:RollingInterval.Day,rollOnFileSizeLimit:true)//自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期
                .CreateLogger();
            logger.Information("信息日志");
            
            var logInfo = new LogInfo
            {
                Index=1,
                Description="日志描述"
            };

            logger.Information("{@logInfo}", logInfo);
            Console.ReadKey();
        }
    }
}

3.4、几种常见的信息输出方式,效果如下图。

代码如下。

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration()
                .WriteTo.Console(theme:AnsiConsoleTheme.Code)
                .WriteTo.File(@"Log/log.txt",rollingInterval:RollingInterval.Day,rollOnFileSizeLimit:true)//自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期
                .CreateLogger();
            logger.Information("信息日志");
            
            var logInfo = new LogInfo
            {
                Index=1,
                Description="日志描述"
            };

            logger.Information("{logInfo}", logInfo);
            logger.Information("{@logInfo}", logInfo);
            logger.Information("{$logInfo}", logInfo);


            logger.Information("-----------------------");

            var dicLogInfo = new Dictionary<string, object>
            {
                {"Index",logInfo.Index },
                {"Description",logInfo.Description },
            };

            logger.Information("{dicLogInfo}", dicLogInfo);
            logger.Information("{@dicLogInfo}", dicLogInfo);
            logger.Information("{$dicLogInfo}", dicLogInfo);
            Console.ReadKey();
        }
    }
}

3.5、SerilogTimings 在应用程序中记录操作的执行时间。‌通过SerilogTimings,‌开发者可以在日志中包含关于操作执行时长的信息,‌这对于性能监控和调试非常有用。‌

示例如下,首先添加NuGet SerilogTimings 2.3.0,如下图。

示例代码如下。

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Themes;
using SerilogTimings;
using SerilogTimings.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration()                
                .WriteTo.Console(theme: AnsiConsoleTheme.Code)
                .WriteTo.File(@"Log/log.txt",rollingInterval:RollingInterval.Day,rollOnFileSizeLimit:true)//自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期
                .CreateLogger();

            logger.Information("信息日志");
            
            var logInfo = new LogInfo
            {
                Index=1,
                Description="日志描述"
            };

            logger.Information("{logInfo}", logInfo);
            logger.Information("{@logInfo}", logInfo);
            logger.Information("{$logInfo}", logInfo);


            logger.Information("-----------------------");

            var dicLogInfo = new Dictionary<string, object>
            {
                {"Index",logInfo.Index },
                {"Description",logInfo.Description },
            };

            logger.Information("{dicLogInfo}", dicLogInfo);
            logger.Information("{@dicLogInfo}", dicLogInfo);
            logger.Information("{$dicLogInfo}", dicLogInfo);

            TimeOper(logger, logInfo);

            Console.ReadKey();
        }

        public static async void TimeOper(ILogger logger, LogInfo logInfo)
        {
            using (logger.TimeOperation("Submitting payment for {Index}", logInfo.Index))
            {
                // Timed block of code goes here
                await Task.Delay(50);
                logger.Information("执行日志{Description}", logInfo.Description);
            }

            var opr=logger.BeginOperation("BeginOperation {Index}", logInfo.Index);
            await Task.Delay(50);
            logger.Information("执行日志 BeginOperation {Description}", logInfo.Description);

            opr.Complete();

        }
    }

}

运行效果如下图。

3.6、使用Destructurama.Attributed 1.0.7 对日志内容进行一些隐藏,由于我这里使用的是.Net Framework4.5,所以用法上不要过度的计较。

NuGet引入 Destructurama.Attributed 1.0.7 如下图。

运行效果如下图。Description中的数据被***替代了。

示例代码如下。

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Themes;
using SerilogTimings;
using SerilogTimings.Extensions;
using Destructurama;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration()
                .Destructure.UsingAttributes()
                .WriteTo.Console(theme: AnsiConsoleTheme.Code)
                .WriteTo.File(@"Log/log.txt",rollingInterval:RollingInterval.Day,rollOnFileSizeLimit:true)//自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期
                .Destructure.ByTransforming<LogInfo>(obj=> new{
                    Index = obj.Index,
                    Description = "***"
                })
                
                .CreateLogger();

            logger.Information("信息日志");
            
            var logInfo = new LogInfo
            {
                Index=1,
                Description="日志描述"
            };

            logger.Information("{logInfo}", logInfo);
            logger.Information("{@logInfo}", logInfo);
            logger.Information("{$logInfo}", logInfo);


            logger.Information("-----------------------");

            var dicLogInfo = new Dictionary<string, object>
            {
                {"Index",logInfo.Index },
                {"Description",logInfo.Description },
            };

            logger.Information("{dicLogInfo}", dicLogInfo);
            logger.Information("{@dicLogInfo}", dicLogInfo);
            logger.Information("{$dicLogInfo}", dicLogInfo);

            TimeOper(logger, logInfo);

            Console.ReadKey();
        }

        public static async void TimeOper(ILogger logger, LogInfo logInfo)
        {
            using (logger.TimeOperation("Submitting payment for {Index}", logInfo.Index))
            {
                // Timed block of code goes here
                await Task.Delay(50);
                logger.Information("执行日志{Description}", logInfo.Description);
            }

            var opr=logger.BeginOperation("BeginOperation {Index}", logInfo.Index);
            await Task.Delay(50);
            logger.Information("执行日志 BeginOperation {Description}", logInfo.Description);

            opr.Complete();

        }
    }

}

3.7、使用异步,Serilog.Sinks.Async 1.5.0 。Serilog.Sinks.Async 是 Serilog 的一个扩展库,‌它提供了异步日志记录的功能。‌使用这个库,‌你可以将日志消息异步地写入到不同的日志存储中,‌比如文件、‌数据库或远程日志服务等。‌这样做的好处是可以提高应用程序的性能,‌因为日志记录操作不会阻塞主线程。‌

NuGet 安装Serilog.Sinks.Async 1.5.0,如下图。

示例代码如下。

cs 复制代码
using Serilog;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Themes;
using SerilogTimings;
using SerilogTimings.Extensions;
using Destructurama;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleAppSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、输出信息到控制台
            ILogger logger = new LoggerConfiguration()
                .Destructure.UsingAttributes()
                //Async 异步写入控制台
                .WriteTo.Async(a=>a.Console(theme: AnsiConsoleTheme.Code))
                //Async 异步写入文件
                .WriteTo.Async(a=>a.File(@"Log/log.txt",rollingInterval:RollingInterval.Day,rollOnFileSizeLimit:true))//自动创建Log文件夹;rollingInterval:RollingInterval.Day,log文件名后自动添加当天日期
                .Destructure.ByTransforming<LogInfo>(obj=> new{
                    Index = obj.Index,
                    Description = "***"
                })
                
                .CreateLogger();

            logger.Information("信息日志");
            
            var logInfo = new LogInfo
            {
                Index=1,
                Description="日志描述"
            };

            logger.Information("{logInfo}", logInfo);
            logger.Information("{@logInfo}", logInfo);
            logger.Information("{$logInfo}", logInfo);


            logger.Information("-----------------------");

            var dicLogInfo = new Dictionary<string, object>
            {
                {"Index",logInfo.Index },
                {"Description",logInfo.Description },
            };

            logger.Information("{dicLogInfo}", dicLogInfo);
            logger.Information("{@dicLogInfo}", dicLogInfo);
            logger.Information("{$dicLogInfo}", dicLogInfo);

            TimeOper(logger, logInfo);
            
            Log.CloseAndFlush();
            //Log.CloseAndFlush(); 在 Serilog 中是一个非常重要的调用,‌它用于确保所有缓存或排队的日志消息都被正确处理并写入到它们的目标存储中。‌
            //当你的应用程序准备关闭或退出时,‌调用这个方法是一个好习惯,‌因为它可以防止日志消息的丢失。‌

            Console.ReadKey();
        }

        public static async void TimeOper(ILogger logger, LogInfo logInfo)
        {
            using (logger.TimeOperation("Submitting payment for {Index}", logInfo.Index))
            {
                // Timed block of code goes here
                await Task.Delay(50);
                logger.Information("执行日志{Description}", logInfo.Description);
            }

            var opr=logger.BeginOperation("BeginOperation {Index}", logInfo.Index);
            await Task.Delay(50);
            logger.Information("执行日志 BeginOperation {Description}", logInfo.Description);

            opr.Complete();

        }
    }

}

3.8、Log.CloseAndFlush(); 在 Serilog 中是一个非常重要的调用,‌它用于确保所有缓存或排队的日志消息都被正确处理并写入到它们的目标存储中。‌当你的应用程序准备关闭或退出时,‌调用这个方法是一个好习惯,‌因为它可以防止日志消息的丢失。‌

4、示例代码可以在这里下载。https://download.csdn.net/download/xingchengaiwei/89687805

其中的ConsoleAppSerilog项目。

相关推荐
张人玉4 小时前
c#WPF基础知识
开发语言·c#·wpf
YuanlongWang5 小时前
C# 基础——值类型与引用类型的本质区别
java·jvm·c#
唐青枫7 小时前
C#.NET FluentValidation 全面解析:优雅实现对象验证
c#·.net
yantuguiguziPGJ13 小时前
WPF 联合 Web 开发调试流程梳理(基于 Microsoft.Web.WebView2)
前端·microsoft·wpf
Aevget13 小时前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(二)
.net·wpf·界面控件·devexpress·ui开发·数据网格
从孑开始16 小时前
ManySpeech.MoonshineAsr 使用指南
人工智能·ai·c#·.net·私有化部署·语音识别·onnx·asr·moonshine
YuanlongWang16 小时前
C# 中,依赖注入(DI)的实现方式
c#
SmartSoftHelp开发辅助优化17 小时前
C# WinForm 编程高手:程序,进程,线程。程序,窗体,UI,后台。是如何协调工作的?深度解析>SmartSoftHelp魔法精灵工作室
microsoft·ui·c#
大美B端工场-B端系统美颜师18 小时前
工控软件开发选择难?Electron、Qt、WPF 对比
qt·electron·wpf
future_studio20 小时前
聊聊 Unity(小白专享、C# 小程序 之 加密存储)
开发语言·小程序·c#