serilog 是一个功能强大的日志记录库,专为 .net 平台设计。它提供了丰富的 api 和可插拔的输出器及格式化器,使得开发者能够轻松定制和扩展日志记录功能。在本文中,我们将探索 serilog 的基础知识、api 使用、配置和一些常见的示例。
1. 日志级别
serilog 支持多个日志级别,按照严重性从高到低排列如下:
- fatal: 程序无法继续运行,必须立即解决的问题。
- error: 发生了错误,需要处理。
- warning: 警告,需关注但不必立即处理。
- information: 提供有用的消息,通常用于调试。
- debug: 调试信息,帮助开发者调试程序。
- verbose: 详细的日志信息,通常用于复杂问题的调试。
2. 日志输出
serilog 支持多种日志输出方式,包括:
- console: 输出到控制台。
- file: 输出到文件。
- seq: 输出到日志收集器 seq。
- elasticsearch: 输出到 elasticsearch。
此外,serilog 也支持自定义日志输出器。
3. 日志格式
serilog 提供了多种格式化日志消息的方式:
- 简单文本格式:常见的日志输出格式。
- json 格式:适合结构化日志。
- message templates 格式:一种灵活的格式,允许在日志消息中插入占位符。
4. 安装
serilog 可以通过 nuget 安装:
install-package serilog
5. 基础使用示例
在应用程序中使用 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 允许设置不同的日志级别。以下示例演示了如何记录各种级别的日志消息:
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 支持消息模板,允许开发者在日志中使用占位符。以下示例展示了如何使用消息模板:
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
设置日志滚动方式。以下示例展示了如何按天滚动文件并设置输出模板:
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();
这将创建类似于 log-20230914.txt
的文件,每天一个新文件。
10. 结构化日志记录
serilog 支持结构化日志记录,这意味着可以将复杂的数据(如对象、集合等)以结构化的方式存储和输出。例如:
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(); } }
此代码只会在控制台输出错误和更高严重级别的日志。
12. 扩展与自定义输出器
serilog 支持自定义输出器,允许开发者将日志输出到不同的目的地(例如 elasticsearch、数据库等)。以下是一个创建自定义控制台输出器的例子:
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. 总结
serilog 是一个功能强大的 .net 日志库,支持丰富的日志记录方式、输出方式和格式化选项。它的可扩展性和灵活性使得开发者能够根据应用程序的需求定制日志记录方式。从简单的控制台日志到复杂的结构化日志和自定义输出器,serilog 都能轻松应对。
希望本文对您理解 serilog 和高效使用该库有所帮助!
到此这篇关于强大的 .net 日志库serilog的文章就介绍到这了,更多相关.net 日志库serilog内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论