七、.net core(.NET 6)使用Serilog进行配置和实现日志记录
使用Serilog来实现日志记录
先安装Serilog六件套神装包:
也可以对个别相应的包进行删除等,都是可以的。例如,标注的1是读取配置文件的,如果不需要通过配置文件进行操作,就可以使用这个包。2是打印到控制台的,如果不需要打印到控制台,也可以不引用。3是写入到文件的,如果不需要写入到文件,也是可以不提供的。我在此处全部引入,方便可以使用多种日志记录方法。Async是异步写入日志,一般需要引入。
我们先在启动项目的Program类里面,新增一些对Serilog的支持操作:
然后,在控制器里面添加对Logger<T>的依赖注入,并写一些不同日志等级的日志记录功能:
然后启动项目,并执行一下该api方法,查看到日志打印的结果:
由于默认消息记录级别是Warn,所以debug消息类型就看不见了。
以及写入文本的日志,由于设定输出到本目录,所以可以在解决方案里面直接看见:
接下来使用配置文件的方式进行日志操作:
本部分serilog配置文件代码:


"Serilog": {
"MinimumLevel": {
"Default": "Debug", //最小日志记录级别
"Override": { //系统日志最小记录级别
"Default": "Warning",
"System": "Warning",
"Microsoft": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" }, //输出到控制台
{
"Name": "Async", //异步写入日志
"Args": {
"configure": [
{
"Name": "File", //输出文件
"Args": {
"path": "log/log.txt",
"outputTemplate": "{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Class:{SourceContext}{NewLine}Message:{Message}{NewLine}{Exception}",
"rollingInterval": "3" //日志文件生成精度:1:年 2:月 3:日 4:小时
}
}
]
}
}
]
}
在Program里面,注释掉原先的代码,然后新增一条通过配置文件进行读取的语句:
因为配置文件里面设置的最小默认等级是Debug,所以现在可以全部打印出来:
配置文件里面配置的rollingInterval值为3,代表每天生成;path代表根目录,设置log/log.txt代表根目录下的log文件夹,按照每天(日期)生成的log开头的txt日志文件。所以我们可以看见在根目录下产生了一个日志文件log20210530.txt:
以上,代表Serilog通过配置文件成功。其中,还可以通过配置文件+启动项配置两个打配合进行配置出更适合自己的日志记录风格,此处不再赘述,欢迎自己尝试。
另外,Serilog还可以实现seq可视化功能,不过seq是收费的,所以这边不做演示。也可以通过ElasticSearch+Kibana进行开发,实现日志可视化和日志搜索引擎功能,该部分功能敬请期待,将来会有这部分教程放出,现在还没到时候。
本篇有关源码:
Program:


public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
} /// <summary>
/// Serilog日志模板
/// </summary>
static string serilogDebug = System.Environment.CurrentDirectory + "\\Log\\Debug\\.log";
static string serilogInfo = System.Environment.CurrentDirectory + "\\Log\\Info\\.log";
static string serilogWarn = System.Environment.CurrentDirectory + "\\Log\\Warning\\.log";
static string serilogError = System.Environment.CurrentDirectory + "\\Log\\Error\\.log";
static string serilogFatal = System.Environment.CurrentDirectory + "\\Log\\Fatal\\.log"; static string SerilogOutputTemplate = "{NewLine}时间:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}日志等级:{Level}{NewLine}所在类:{SourceContext}{NewLine}日志信息:{Message}{NewLine}{Exception}"; public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) // 添加Autofac
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseUrls("http://*:35678")
.UseSerilog((context, logger) =>//注册Serilog
{
logger.ReadFrom.Configuration(context.Configuration);
logger.Enrich.FromLogContext(); //logger.WriteTo.Console(); // 输出到Console控制台
//// 输出到配置的文件日志目录
//logger.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.Async(a => a.File(serilogDebug, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate)))
// .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.Async(a => a.File(serilogInfo, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate)))
// .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.Async(a => a.File(serilogWarn, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate)))
// .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.Async(a => a.File(serilogError, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate)))
// .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.Async(a => a.File(serilogFatal, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate)));
}); });
}
WSKController:


[Route("api/[controller]")]
[ApiController]
public class WSKController : ControllerBase
{ private readonly ITestAutofac _autofac;
private readonly ILogger<WSKController> _logger;
public WSKController(ITestAutofac autofac, ILogger<WSKController> logger) {
_autofac = autofac;
_logger = logger;
} [HttpPost]
public IActionResult HelloWorld()
{
// _autofac.Test(); _logger.LogInformation("Info Message……");
_logger.LogWarning("Warning Message……");
_logger.LogDebug("Debug Message……");
_logger.LogError("Error Message……"); return Ok();
} }
最后,如果本文章对君有用,欢迎点赞、评论和打赏~~
版权所有,转载请注明出处:https://www.cnblogs.com/weskynet/p/14829299.html
七、.net core(.NET 6)使用Serilog进行配置和实现日志记录的更多相关文章
- ASP.NET Core 异常处理与日志记录
1. ASP.NET Core 异常处理与日志记录 1.1. 异常处理 1.1.1. 异常产生的原因及处理 1.1.2. ASP.NET Core中启动开发人员异常页面 1.2. 日志记录 1.2.1 ...
- Net Core平台灵活简单的日志记录框架NLog+Mysql组合初体验
Net Core平台灵活简单的日志记录框架NLog初体验 前几天分享的"[Net Core集成Exceptionless分布式日志功能以及全局异常过滤][https://www.cnblog ...
- ASP.NET Core 集成测试中通过 Serilog 向控制台输出日志
日志是程序员的雷达,不仅在生产环境中需要,在集成测试环境中也需要,可以在持续集成失败后帮助定位问题.与生产环境不同,在集成测试环境中使用控制台输出日志更方便,这样可以通过持续集成 runner 执行 ...
- Serilog 是 ASP.NET Core 的一个插件,可以简化日志记录
[翻译] ASP.NET Core 利用 Docker.ElasticSearch.Kibana 来记录日志 原文: Logging with ElasticSearch, Kibana, ASP.N ...
- .Net Core 3.0 使用 Serilog 把日志记录到 SqlServer
Serilog简介 Serilog是.net中的诊断日志库,可以在所有的.net平台上面运行.Serilog支持结构化日志记录,对复杂.分布式.异步应用程序的支持非常出色.Serilog可以通过插件的 ...
- 在 ASP.NET Core 中使用 Serilog 进行日志记录
目录 从 NuGet 安装 Serilog 在 Main函数 中配置 Serilog 在项目中使用 Serilog 进行日志输出 从 NuGet 安装 Serilog 核心的包是 Serilog 和 ...
- .Net Core项目中整合Serilog
前言:Serilog是.NET应用程序的诊断日志记录库.它易于设置,具有简洁的API,并且可以在所有最新的.NET平台上运行.尽管即使在最简单的应用程序中它也很有用,但当对复杂的,分布式的和异步的应用 ...
- ASP.NET Core 2.2 基础知识(六) 配置(内含MySql+EF)
先上一段代码,了解一下 .NET Core 配置数据的结构. 新建一个 控制台项目,添加一个文件 json.json ,文件内容如下: { "country": "cn& ...
- (14)ASP.NET Core 中的日志记录
1.前言 ASP.NET Core支持适用于各种内置和第三方日志记录提供应用程序的日志记录API.本文介绍了如何将日志记录API与内置提供应用程序一起使用. 2.添加日志提供程序 日志记录提供应用程序 ...
随机推荐
- Borrowers UVA - 230
I mean your borrowers of books - those mutilators of collections, spoilers of the symmetry of shel ...
- 幻读:听说有人认为我是被MVCC干掉的
@ 目录 前言 系列文章 一.我是谁? 二.为什么有人会认为我是被MVCC干掉的 三.我真的是被MVCC解决的? 四.再聊当前读.快照读 当前读 快照读 五.告诉你们吧!当前读的情况下我是被next- ...
- os shutil 模块
OS --- 操作系统接口 os.system(command) # 在python中执行系统指令 os.popen(command[, mode[, bufsize]]) #os.popen() 方 ...
- 1091 Acute Stroke
One important factor to identify acute stroke (急性脑卒中) is the volume of the stroke core. Given the re ...
- new word
strategy: a plan of action or policy designed to achieve a major or overall aim.
- SpringBoot自定义配置以及IDEA配置提示
本篇文章将会讲解在springboot项目中如何实现自定义配置以及在IDEA或者Eclipse中实现配置项提示,就像spring的配置提示一样 想要做到这点其实非常简单 1.添加依赖 <depe ...
- php自定义配置文件简单写法
1 <?php 2 header("Content-type:text/html;charset=utf-8"); 3 4 $q = getconfig('rr'); 5 e ...
- overflow和absolute之间的问题,transfrom可以解决
CSS代码: .overflow { width: 191px; height: 191px; border: 2px solid #beceeb; overflow: hidden; } .over ...
- Android NDK编程之Android.mk和Application.mk
Android编程使用NDK必须创建一个jni文件夹,并且jni文件里一般包含有C/C++的源码文件.Android..mk文件.Application.mk文件(可选),Android.mk文件的编 ...
- 路由器逆向分析------QEMU的下载和安装(Linux平台)
本文博客地址:http://blog.csdn.net/qq1084283172/article/details/68953160 一.QEMU源码的下载和编译 QEMU源码的github下载地址:h ...