惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Hacker News
The Hacker News
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
Cisco Talos Blog
Cisco Talos Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
PCI Perspectives
PCI Perspectives
Cyberwarzone
Cyberwarzone
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
G
GRAHAM CLULEY
Help Net Security
Help Net Security
Scott Helme
Scott Helme
V2EX - 技术
V2EX - 技术
Security Latest
Security Latest
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Hacker News: Ask HN
Hacker News: Ask HN
C
Cybersecurity and Infrastructure Security Agency CISA
O
OpenAI News
L
LINUX DO - 热门话题
T
Tor Project blog
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
Security Archives - TechRepublic
Security Archives - TechRepublic
量子位
I
InfoQ
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
P
Proofpoint News Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Application and Cybersecurity Blog
Application and Cybersecurity Blog
雷峰网
雷峰网
Cloudbric
Cloudbric
Microsoft Azure Blog
Microsoft Azure Blog
D
Docker
T
Threat Research - Cisco Blogs
Blog — PlanetScale
Blog — PlanetScale
H
Heimdal Security Blog
T
Tenable Blog
Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
美团技术团队
S
Secure Thoughts
Know Your Adversary
Know Your Adversary
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 广阔之海

Halcon的三角函数 Halcon轮廓插值方法 C# 控件选项变化事件处理 深度学习执行速度不稳定的解决方法 Halcon - 深度学习 - 目标分类 Halcon 画一个时钟 Halcon 解方程(solve_matrix) Halcon 生成标定板 Halcon 中的形态学 Halcon的提取中心线算法 C# 消灭switch的面向映射编程 C#中Task的用法 Halcon 通过坐标轴过滤点云数据 Halcon图像投影映射 C# 获取MySql的数据库结构信息 C# HttpClient的使用方法总结 MySql字符集导致特殊字符保存出错问题处理 Asp.Net Core 动态生成WebApi Asp.Net Core WebApi中集成Jwt认证
C# 使用Serilog日志框架
广阔之海 · 2022-11-26 · via 博客园 - 广阔之海

Serilog是一款配置方便,使用灵活的日志框架,使用方法如下:
1、日志输出到控制台,需要使用Nuget安装Serilog和Serilog.Sinks.Console两个包

            // 初始化日志的共享实例
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .CreateLogger();
            // 写入日志
            Log.Information("Info");

2、日志输出到文件,需要安装Serilog.Sinks.File包

            // 初始化日志的共享实例
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .WriteTo.File("logs/app.log", 
                    rollingInterval: RollingInterval.Day, // 每天一个日志文件
                    shared: true    // 允许其他进程共享日志文件
                ).CreateLogger();
            // 写入日志
            Log.Information("Info");

3、可以通过配置,让不同日志级别输出到不同的日志文件

       // 初始化日志的共享实例
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                // 调试日志
                .WriteTo.Logger(x => x
                    .Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Debug)
                    .WriteTo.File("logs/debug.log", rollingInterval: RollingInterval.Day, shared: true)
                // 错误日志
                ).WriteTo.Logger(x => x
                    .Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error)
                    .WriteTo.File("logs/error.log", rollingInterval: RollingInterval.Day, shared: true)
                // 应用日志
                ).WriteTo.Logger(x => x
                    .Filter.ByIncludingOnly(e => e.Level != Serilog.Events.LogEventLevel.Debug &&
                        e.Level != Serilog.Events.LogEventLevel.Error)
                    .WriteTo.File("logs/app.log", rollingInterval: RollingInterval.Day, shared: true)
                ).CreateLogger();
            // 写入日志到 app.log
            Log.Information("Info");
            // 写入日志到 debug.log
            Log.Debug("Debug");
            // 写入日志到 error.log
            Log.Error("Error");

4、写入日志到SqlServer

            // 写入数据库的配置
            var sinkOpts = new MSSqlServerSinkOptions();
            sinkOpts.TableName = "logs";            // 日志表名
            sinkOpts.AutoCreateSqlTable = true;     // 自动创建表
            // 列配置
            var columnOpts = new ColumnOptions();
            columnOpts.Store.Remove(StandardColumn.Exception);  // 去掉异常列
            columnOpts.Store.Remove(StandardColumn.Properties); // 去掉属性列
            columnOpts.Exception.DataLength = 2048;             // 指定列的长度
            columnOpts.TimeStamp.NonClusteredIndex = true;      // 去掉时间戳的聚集索引
            // 初始化日志的共享实例
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .WriteTo.MSSqlServer(
                        connectionString: ConfigurationManager.ConnectionStrings["Default"].ConnectionString,
                        sinkOptions: sinkOpts,
                        columnOptions: columnOpts
                 ).CreateLogger();
            // 写入日志
            Log.Information("Info");

执行代码后,发现日志表并没有添加到数据库,也没有任何异常信息,我们可以添加以下代码调试Serilog

            Serilog.Debugging.SelfLog.Enable(msg =>
            {
                Debug.Print(msg);
                Debugger.Break();
            });

获取到如下的错误信息:

2022-11-26T09:34:53.6107406Z Unable to write 1 log events to the database due to following error: A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - 证书链是由不受信任的颁发机构颁发的。)

需要在连接字符串添加信任服务器证书的配置:TrustServerCertificate=True;

就能在SqlServer中创建日志表并写入日志。