強(qiáng)大的 .NET 日志庫Serilog詳解
Serilog 是一個功能強(qiáng)大的日志記錄庫,專為 .NET 平臺設(shè)計。它提供了豐富的 API 和可插拔的輸出器及格式化器,使得開發(fā)者能夠輕松定制和擴(kuò)展日志記錄功能。在本文中,我們將探索 Serilog 的基礎(chǔ)知識、API 使用、配置和一些常見的示例。
1. 日志級別
Serilog 支持多個日志級別,按照嚴(yán)重性從高到低排列如下:
- Fatal: 程序無法繼續(xù)運(yùn)行,必須立即解決的問題。
- Error: 發(fā)生了錯誤,需要處理。
- Warning: 警告,需關(guān)注但不必立即處理。
- Information: 提供有用的消息,通常用于調(diào)試。
- Debug: 調(diào)試信息,幫助開發(fā)者調(diào)試程序。
- Verbose: 詳細(xì)的日志信息,通常用于復(fù)雜問題的調(diào)試。
2. 日志輸出
Serilog 支持多種日志輸出方式,包括:
- Console: 輸出到控制臺。
- File: 輸出到文件。
- Seq: 輸出到日志收集器 Seq。
- Elasticsearch: 輸出到 Elasticsearch。
此外,Serilog 也支持自定義日志輸出器。
3. 日志格式
Serilog 提供了多種格式化日志消息的方式:
- 簡單文本格式:常見的日志輸出格式。
- JSON 格式:適合結(jié)構(gòu)化日志。
- Message Templates 格式:一種靈活的格式,允許在日志消息中插入占位符。
4. 安裝
Serilog 可以通過 NuGet 安裝:
Install-Package Serilog
5. 基礎(chǔ)使用示例
在應(yīng)用程序中使用 Serilog 十分簡單。以下是一個簡單的控制臺日志輸出示例:
using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.CreateLogger();
Log.Information("Hello, Serilog!");
Log.CloseAndFlush();
}
}此代碼將在控制臺輸出 Hello, Serilog!。
6. 日志級別示例
Serilog 允許設(shè)置不同的日志級別。以下示例演示了如何記錄各種級別的日志消息:
using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Console()
.CreateLogger();
Log.Verbose("This is a verbose log message.");
Log.Debug("This is a debug log message.");
Log.Information("This is an informational log message.");
Log.Warning("This is a warning log message.");
Log.Error("This is an error log message.");
Log.Fatal("This is a fatal log message.");
Log.CloseAndFlush();
}
}7. 消息模板
Serilog 支持消息模板,允許開發(fā)者在日志中使用占位符。以下示例展示了如何使用消息模板:
using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
Log.Information("Hello, {Name}!", "Serilog");
Log.CloseAndFlush();
}
}上述代碼將在控制臺輸出如下格式的日志:
2023-09-15 22:23:54.576 +08:00 [INF] Hello, Serilog!
8. 日志屬性
Serilog 支持在日志中添加附加屬性。以下示例展示了如何記錄額外的信息:
using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.CreateLogger();
Log.Information("Processed {@Count} records in {Time} ms.", new { Count = 10, Time = 123 });
Log.CloseAndFlush();
}
}此代碼會輸出:
Processed { Count: 10, Time: 123 } records in 0 ms.
9. 文件輸出配置
Serilog 允許將日志輸出到文件,并通過 rollingInterval 設(shè)置日志滾動方式。以下示例展示了如何按天滾動文件并設(shè)置輸出模板:
Log.Logger = new LoggerConfiguration()
.WriteTo.File(
$"logs\\log-.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
Log.Information("This is a log message!");
Log.CloseAndFlush();這將創(chuàng)建類似于 log-20230914.txt 的文件,每天一個新文件。
10. 結(jié)構(gòu)化日志記錄
Serilog 支持結(jié)構(gòu)化日志記錄,這意味著可以將復(fù)雜的數(shù)據(jù)(如對象、集合等)以結(jié)構(gòu)化的方式存儲和輸出。例如:
using Serilog;
class Program
{
static void Main()
{
var weather = new WeatherForecast
{
Date = DateTime.Now,
TemperatureC = 22,
Summary = "Sunny"
};
Log.Information("Weather forecast: {@Weather}", weather);
Log.CloseAndFlush();
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}此代碼將輸出類似于:
Weather forecast: {"Date":"2023-09-15T22:39:53.8634787+08:00","TemperatureC":22,"Summary":"Sunny","$type":"WeatherForecast"}
11. 日志過濾
Serilog 允許使用過濾器控制輸出。以下示例僅輸出錯誤級別以上的日志:
using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.Filter.ByIncludingOnly(logEvent => logEvent.Level >= LogEventLevel.Error)
.CreateLogger();
Log.Verbose("This is a verbose log message.");
Log.Error("This is an error log message.");
Log.CloseAndFlush();
}
}此代碼只會在控制臺輸出錯誤和更高嚴(yán)重級別的日志。
12. 擴(kuò)展與自定義輸出器
Serilog 支持自定義輸出器,允許開發(fā)者將日志輸出到不同的目的地(例如 Elasticsearch、數(shù)據(jù)庫等)。以下是一個創(chuàng)建自定義控制臺輸出器的例子:
using Serilog;
using Serilog.Configuration;
using Serilog.Events;
public static class CustomConsoleSinkExtensions
{
public static LoggerConfiguration CustomConsole(
this LoggerSinkConfiguration sinkConfiguration,
ITextFormatter formatter = null,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
{
return sinkConfiguration.Sink(
new CustomConsoleSink(formatter),
restrictedToMinimumLevel);
}
}
public class CustomConsoleSink : ILogEventSink
{
private readonly ITextFormatter _formatter;
public CustomConsoleSink(ITextFormatter formatter)
{
_formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
}
public void Emit(LogEvent logEvent)
{
var message = new StringWriter();
_formatter.Format(logEvent, message);
Console.WriteLine(message.ToString());
}
}然后可以通過以下方式將其添加到日志配置中:
Log.Logger = new LoggerConfiguration()
.WriteTo.CustomConsole()
.CreateLogger();13. 總結(jié)
Serilog 是一個功能強(qiáng)大的 .NET 日志庫,支持豐富的日志記錄方式、輸出方式和格式化選項(xiàng)。它的可擴(kuò)展性和靈活性使得開發(fā)者能夠根據(jù)應(yīng)用程序的需求定制日志記錄方式。從簡單的控制臺日志到復(fù)雜的結(jié)構(gòu)化日志和自定義輸出器,Serilog 都能輕松應(yīng)對。
希望本文對您理解 Serilog 和高效使用該庫有所幫助!
到此這篇關(guān)于強(qiáng)大的 .NET 日志庫Serilog的文章就介紹到這了,更多相關(guān).NET 日志庫Serilog內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
.NET?Core利用?AsyncLocal?實(shí)現(xiàn)共享變量的代碼詳解
在Web?應(yīng)用程序中,我們經(jīng)常會遇到這樣的場景,如用戶信息,租戶信息本次的請求過程中都是固定的,我們希望是這種信息在本次請求內(nèi),一次賦值,到處使用。本文就來探討一下,如何在.NET?Core?下去利用AsyncLocal?實(shí)現(xiàn)全局共享變量2022-04-04
asp.net(c#)實(shí)現(xiàn)從sqlserver存取二進(jìn)制圖片的代碼
有一個員工表Employee,需要保存員工照片(Photo)到數(shù)據(jù)庫(sql server)上。員工照片對應(yīng)的字段是varbinary(max),也就是要存成二進(jìn)制文件類型(這和以前討巧地存圖片文件路徑就不相同了),默認(rèn)可以為空。2011-09-09
Visual Studio 2017開發(fā)環(huán)境的安裝圖文教程
Visual Studio 2017是微軟于2017年3月8日正式推出的新版本,是迄今為止 最具生產(chǎn)力 的 Visual Studio 版本。這篇文章主要介紹了Visual Studio 2017開發(fā)環(huán)境的安裝,需要的朋友可以參考下2017-11-11
Visual Studio 2017 針對移動開發(fā)的新特性匯總
Visual Studio是世界上最好的IDE之一,下面就讓我們一起來看看Visual Studio 2017中有哪些功能使得移動開發(fā)變得更加容易,感興趣的朋友通過本文學(xué)習(xí)下吧2017-05-05
一步步打造簡單的MVC電商網(wǎng)站BooksStore(4)
這篇文章主要和大家一起一步步打造一個簡單的MVC電商網(wǎng)站,MVC電商網(wǎng)站BooksStore第四篇,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
asp.net中ADO SQL數(shù)據(jù)庫 筆記匯總 持續(xù)更新中
asp.net中ADO SQL數(shù)據(jù)庫 筆記匯總 持續(xù)更新中,需要的朋友可以參考下2012-07-07
Entity?Framework實(shí)現(xiàn)數(shù)據(jù)遷移
本文詳細(xì)講解了Entity?Framework實(shí)現(xiàn)數(shù)據(jù)遷移的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03

