而在实际项目开发中,使用第三方日志框架来记录日志也是非常多的,首先一般基础的内置日志记录器在第三方日志框架中都有实现,然后很多第三方日志框架在功能上更强大和丰富,能满足我们更多的项目分析和诊断的需求。常用的有log4net,更复杂的elk,项目中有用到exceptionless。下面说的是serilog:

首先建个aspnetcorewebapi6.0的项目

安装组件:

Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)

using Serilog;
using Serilog.Events; // Setup serilog in a two-step process. First, we configure basic logging
// to be able to log errors during ASP.NET Core startup. Later, we read
// log settings from appsettings.json. Read more at
// https://github.com/serilog/serilog-aspnetcore#two-stage-initialization.
// General information about serilog can be found at
// https://serilog.net/
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger(); try
{
Log.Information("Starting the web host");
var builder = WebApplication.CreateBuilder(args);
// Full setup of serilog. We read log settings from appsettings.json
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
// Add services to the container. builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline.
app.UseSerilogRequestLogging(configure =>
{
configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
} app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
}
catch
(Exception ex)
{
Log.Fatal(ex, "Host terminated unexpexctedly");
}
finally
{
Log.CloseAndFlush();
}
{
//"Logging": {
// "LogLevel": {
// "Default": "Information",
// "Microsoft.AspNetCore": "Warning"
// }
//},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ],
"MinimumLevel": "Information",
// Where do we want to write our logs to? Choose from a large number of sinks:
// https://github.com/serilog/serilog/wiki/Provided-Sinks.
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": { "path": "Logs/log.txt" }
},
{
"Name": "Seq",
"Args": { "serverUrl": "http://localhost:8888" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AspNetCoreSerilogDemo"
}
},
"AllowedHosts": "*"
}

运行结果如下,已替换系统自带information:

请求跟踪分析:

using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreSerilogDemo.Controllers
{
[ApiController]
[Route("[controller]")]
public class SeriLogDemoController : ControllerBase
{ private readonly ILogger<SeriLogDemoController> _logger; public SeriLogDemoController(ILogger<SeriLogDemoController> logger)
{
_logger = logger;
} [HttpGet]
public string String()
{
_logger.LogInformation("this is serilog...");
return "Suscess";
} }
}

配置文件里面输出路径有"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ],所以同样会输出到日志文件中,指定路径和文件名:

更多更详细功能参考:

Serilog — simple .NET logging with fully-structured events

Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)

示例代码:

exercise/AspNetCoreSerilogDemo at master · liuzhixin405/exercise (github.com)

aspnetcore 使用serilog日志的更多相关文章

  1. ASP.NET Core MVC之Serilog日志处理,你了解多少?

    前言 本节我们来看看ASP.NET Core MVC中比较常用的功能,对于导入和导出目前仍在探索中,项目需要自定义列合并,所以事先探索了如何在ASP.NET Core MVC进行导入.导出,更高级的内 ...

  2. .NET Worker Service 添加 Serilog 日志记录

    前面我们了解了 .NET Worker Service 的入门知识[1] 和 如何优雅退出 Worker Service [2],今天我们接着介绍一下如何为 Worker Service 添加 Ser ...

  3. 十八、.net core(.NET 6)搭建ElasticSearch(ES)系列之使用Logstash通过Rabbitmq接收Serilog日志到ES

    使用Logstash通过Rabbitmq接收Serilog日志到ES 首先,要部署logstash 为了与前面的ElasticSearch版本保持一致,此处Logstash下载的版本也是7.13.1, ...

  4. AspNetCore 使用NLog日志,NLog是基于.NET平台开的类库!(又一神器)

    NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码. NLog是一个简单灵活的.NET日志记录类库.通过使用NLog,我们可以在任何一种.NET语言中 ...

  5. EL+Serilog日志

    简介 Elasticsearch 是一个实时的分布式搜索分析引擎,它能让你以前所未有的速度和规模,去探索你的数据. 它被用作全文检索.结构化搜索.分析以及这三个功能的组合: 安装 Elasticsea ...

  6. ASP.NET Core 集成测试中通过 Serilog 向控制台输出日志

    日志是程序员的雷达,不仅在生产环境中需要,在集成测试环境中也需要,可以在持续集成失败后帮助定位问题.与生产环境不同,在集成测试环境中使用控制台输出日志更方便,这样可以通过持续集成 runner 执行 ...

  7. TraceID在AspNETCore日志排障中的应用

    前言 .NetCore日志,相信大家多少都接触过,博客园有关 ① AspNetCore依赖注入第三方日志组件   ②第三方日志组件Nlog,Serilog 应用方法的博文层出不穷. 结合程序的部署结构 ...

  8. 如何利用Serilog的RequestLogging来精简ASP.NET Core的日志输出

    这是该系列的第一篇文章:在ASP.NET Core 3.0中使用Serilog.AspNetCore. 第1部分-使用Serilog RequestLogging来简化ASP.NET Core的日志输 ...

  9. 基于.NetCore3.1系列 —— 日志记录之初识Serilog

    一.前言 对内置日志系统的整体实现进行了介绍之后,可以通过使用内置记录器来实现日志的输出路径.而在实际项目开发中,使用第三方日志框架(如: Log4Net.NLog.Loggr.Serilog.Sen ...

随机推荐

  1. 什么是css Modules

    具体请参考阮一峰老师的博客(http://www.ruanyifeng.com/blog/2016/06/css_modules.html)

  2. vue2.0与vue3.0项目创建

    脚手架安装与卸载 安装 npm install -g vue-cli //or npm install -g @vue/cli 卸载 npm uninstall -g vue-cli //or npm ...

  3. 动静分离、Rewirte、HTTPS

    目录 Nginx动静分离技术 示例搭建步骤 部署NFS 静态资源共享 部署代理服务器 Rewrite(重点) Rewrite基本概述 rewrite语法 rewrite标记Flag last和brea ...

  4. 转雅虎web前端网站优化 34条军规

    雅虎给出了优化网站加载速度的34条法则(包括Yslow规则22条) 详细说明,下载转发 ponytail 的译文 1.Minimize HTTP Requests 减少HTTP请求 图片.css.sc ...

  5. 《剑指offer》面试题38. 字符串的排列

    问题描述 输入一个字符串,打印出该字符串中字符的所有排列. 你可以以任意顺序返回这个字符串数组,但里面不能有重复元素. 示例: 输入:s = "abc" 输出:["abc ...

  6. 探索新冠肺炎(COVID-19)对全球航班的影响

    Cesium中文网:http://cesiumcn.org/ | 国内快速访问:http://cesium.coinidea.com/ 随着今天从欧洲到美国的旅行限制生效,以及为了减缓新冠病毒的传播更 ...

  7. 513. Find Bottom Left Tree Value

    Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...

  8. C++虚函数和静态函数调用方式

    简单情况: #include<iostream> using namespace std; class A { public: virtual void foo() { cout < ...

  9. Filter+Redis解决项目之间调用的幂等性

    幂等(idempotent.idempotence)是一个数学与计算机学概念,常见于抽象代数中. 在编程中一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同 在项目远程调用中,如果接 ...

  10. kdj

    随机指标KDJ一般是用于股票分析的统计体系,根据统计学原理,通过一个特定的周期(常为9日.9周等)内出现过的最高价.最低价及最后一个计算周期的收盘价及这三者之间的比例关系,来计算最后一个计算周期的未成 ...