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、将信息输入到控制台,代码如下。

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文件名后自动添加当天日期 

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类,代码如下。

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函数代码如下。

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、几种常见的信息输出方式,效果如下图。

代码如下。

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,如下图。

示例代码如下。

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中的数据被***替代了。

 示例代码如下。

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,如下图。

 示例代码如下。

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项目。

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为风而战

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值