appsettings.json配置Serilog
{ //"Logging": { // "LogLevel": { // "Default": "Information", // "Microsoft.AspNetCore": "Warning" // } //}, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Information", "Microsoft.AspNetCore": "Warning", "System": "Warning" } }, "WriteTo": [ //{ "Name": "Console" }, //{ // "Name": "File", // "Args": { // "path": "./Logs/log-.txt", // "rollingInterval": "Day", // "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" // } //}, { "Name": "MSSqlServer", "Args": { "connectionString": "Server=DESKTOP-DABHN6U\\MSSQLSERVER2014;uid=sa;pwd=Lz38275292;database=NewAps;MultipleActiveResultSets=true;", "tableName": "Log", "autoCreateSqlTable": true //自动创建日志表Log } } ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "Properties": { "Application": "WepAPI" } }, "AllowedHosts": "*", }
使用 Serilog 日志服务,在 Program.cs 文件中添加以下代码
//为了使用appsettings.json配置和依赖注入,分两步初始化Serilog日志 //1.Serilog 日志,1.配置初始“引导”记录器 Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .CreateBootstrapLogger(); //2.Serilog 日志 创建最终记录器 builder.Host.UseSerilog((context, services, configuration) => configuration.ReadFrom.Configuration(context.Configuration) .ReadFrom.Services(services) .Enrich.FromLogContext() .WriteTo.Console());
消费 Serilog 日志
//日志测试控制器 [Route("api/[controller]")] [ApiController] public class LoggerTestController : ControllerBase { private readonly ILogger<LoggerTestController> _logger; public LoggerTestController(ILogger<LoggerTestController> logger) { _logger = logger; } [HttpGet] public async Task WriterLogger() { int eventId = 3721; _logger.LogInformation(eventId, "升级到最新版本({version})", "1.0.0.rc2"); _logger.LogWarning(eventId, "并发量接近上限({maximum}) ", 200); _logger.LogError(eventId, "数据库连接失败(数据库:{Database},用户名:{User})", "TestDb", "sa"); } }
提示:常用第三方日志提供程序:NLog、Serilog、Log4Net
手动创建日志表Sql(可选):
/****** Object: Table [dbo].[Log] Script Date: 2022-09-26 18:24:33 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Log]( [Id] [int] IDENTITY(1,1) NOT NULL, [Message] [nvarchar](max) NULL, [MessageTemplate] [nvarchar](max) NULL, [Level] [nvarchar](max) NULL, [TimeStamp] [datetime] NULL, [Exception] [nvarchar](max) NULL, [Properties] [nvarchar](max) NULL, CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
标签:Log,Serilog,appsettings,json,max,logger,NULL,日志 From: https://www.cnblogs.com/friend/p/16731931.html