而在实际项目开发中,使用第三方日志框架来记录日志也是非常多的,首先一般基础的内置日志记录器在第三方日志框架中都有实现,然后很多第三方日志框架在功能上更强大和丰富,能满足我们更多的项目分析和诊断的需求。常用的有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. PPT制作图片磨砂玻璃艺术效果

    如果图片损害,点击链接:https://www.toutiao.com/i6488928834799272462/ 选择"插入"选项卡,"图像"功能组,&quo ...

  2. fis学习

    http://fis.baidu.com/docs/beginning/getting-started.html#md5 还是喜欢时间戳?没问题,FIS也可以满足你的需求,点击这里

  3. 关于在Vue中使用WebScoket的随笔

    声明:请勿直接复制粘贴抄袭文章,若有需要,请规范转载,注明出处,谢谢! ---------------------------------------------------------------- ...

  4. Mybatis 学习记录

    1.先放上mybatis官网地址: https://mybatis.org/mybatis-3/zh/index.html 2.mybatis源码和有关包下载地址(GitHub): https://g ...

  5. java继承成员变量特点

    1 /* 2 * 在子父类中,成员的特点体现. 3 * 1,成员变量. 4 * 2,成员函数. 5 * 3,构造函数. 6 */ 7 8 //1, 成员变量. 9 /* 10 * 当本类的成员和局部变 ...

  6. 集合框架-ListIterator接口

    1 package cn.itcast.p4.list.demo; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 imp ...

  7. java-异常-异常处理原则

    1 异常处理的原则: 2 * 1,函数内部如果抛出需要检测的异常,那么函数上必须要声明. 3 * 否则必须在函数内用trycatch捕捉,否则编译失败. 4 * 5 * 2,如果调用到了声明异常的函数 ...

  8. Django settings.py配置文件

    import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 这里用到了python中一个神奇的变量 file 这个变量可以获取到当前 ...

  9. Windows如何搭建SSL通信(非Web)

    自己研究了会儿,把结论发出来给有需要的人 第一步:准备环境 首先需要一台服务器(这不是废话吗),我这边用的windows2003, 还需要一台客户端,我用的是windwos2008 第二步:服务器环境 ...

  10. ERNIE代码解析

    原创作者 |疯狂的Max ERNIE代码解读 考虑到ERNIE使用BRET作为基础模型,为了让没有基础的NLPer也能够理解代码,笔者将先为大家简略的解读BERT模型的结构,完整代码可以参见[1]. ...