Serilog日志组件使用



builder.Logging.ClearProviders(); // 移除默认的日志提供程序 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Warning) .WriteTo.Console() .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")) { // 基本配置 AutoRegisterTemplate = true, // 自动创建/更新索引模板 (适用于 ES 7.x/8.x) AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7, // 指定模板版本 (ESv8 for ES 8.x, ESv7 for ES 7.x) IndexFormat = "logs-{0:yyyy.MM.dd}", // 索引名称格式,按天滚动 TemplateName = "serilog-events-template", // 模板名称 NumberOfShards = 1, // 分片数 NumberOfReplicas = 1, // 副本数 // 批处理配置 BatchPostingLimit = 1000, // 每批发送的最大日志数 Period = TimeSpan.FromSeconds(5), // 批处理间隔时间 // 连接和重试配置 ConnectionTimeout = TimeSpan.FromSeconds(10), // EmitLogEvent = true, // 是否发送完整的 LogEvent 对象 (默认 true) // 认证 (如果 Elasticsearch 需要) // 如果你的 Elasticsearch 有用户名密码 // ModifyConnectionSettings = connectionConfiguration => connectionConfiguration // .BasicAuthentication("your-username", "your-password"), // 如果是 HTTPS 且需要忽略证书验证 (仅限开发环境!) // ModifyConnectionSettings = connectionConfiguration => connectionConfiguration // .ServerCertificateValidationCallback((sender, certificate, chain, errors) => true), // (可选) 如果需要配置特定的序列化或日志属性 // CustomFormatter = new ElasticsearchJsonFormatter(), // 使用默认或自定义格式化器 }) .WriteTo.MSSqlServer(connectionString: "Server=localhost;Database=LogDb;Integrated Security=SSPI;Encrypt=True; TrustServerCertificate=True;" , sinkOptions: new MSSqlServerSinkOptions { TableName = "LogEvents", AutoCreateSqlTable = true }) .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(); builder.Host.UseSerilog(dispose: true);




  app.UseSerilogRequestLogging(); //一定不能少这一句






posted @ 2025-08-20 19:39  网络来者  阅读(7)  评论(0)    收藏  举报