77 lines
3.4 KiB
C#
77 lines
3.4 KiB
C#
using Amazon.SecurityToken.Model;
|
|
using DocumentFormat.OpenXml.Bibliography;
|
|
using IRaCIS.Core.Domain.Share;
|
|
using Microsoft.Extensions.Configuration.Json;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Serilog;
|
|
using Serilog.Events;
|
|
using Serilog.Formatting.Compact;
|
|
using Serilog.Formatting.Display;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
|
|
namespace IRaCIS.Core.API
|
|
{
|
|
public class SerilogExtension
|
|
{
|
|
|
|
public static void AddSerilogSetup(string environment)
|
|
{
|
|
|
|
var config = new LoggerConfiguration()
|
|
.MinimumLevel.Information()
|
|
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
|
|
// Filter out ASP.NET Core infrastructre logs that are Information and below 日志太多了 一个请求 记录好几条
|
|
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
|
|
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Warning)
|
|
.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Warning)
|
|
.MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Warning)
|
|
.MinimumLevel.Override("Hangfire", LogEventLevel.Warning)
|
|
.Enrich.FromLogContext()
|
|
.Filter.ByExcluding(logEvent => logEvent.Properties.ContainsKey("RequestPath") && logEvent.Properties["RequestPath"].ToString().Contains("/health"))
|
|
.WriteTo.Console()
|
|
.WriteTo.File($"{AppContext.BaseDirectory}Serilogs/.log", rollingInterval: RollingInterval.Day);
|
|
|
|
#region 根据环境配置是否打开错误发送邮件通知
|
|
|
|
//读取配置文件
|
|
var configuration = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = $"appsettings.{environment}.json", ReloadOnChange = true }).Build();
|
|
|
|
// 手动绑定配置
|
|
var emailConfig = new SystemEmailSendConfig();
|
|
configuration.GetSection("SystemEmailSendConfig").Bind(emailConfig);
|
|
|
|
if (emailConfig.IsOpenErrorNoticeEmail)
|
|
{
|
|
config.WriteTo.Email(options: new Serilog.Sinks.Email.EmailSinkOptions()
|
|
{
|
|
From = emailConfig.FromEmail,
|
|
To = emailConfig.ErrorNoticeEmailList,
|
|
Host = emailConfig.Host,
|
|
Port = emailConfig.Port,
|
|
Subject = new MessageTemplateTextFormatter("Log Alert - 系统发生了异常,请核查"),
|
|
Credentials = new NetworkCredential(emailConfig.FromEmail, emailConfig.AuthorizationCode)
|
|
|
|
}, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error);
|
|
}
|
|
#endregion
|
|
|
|
Log.Logger = config.CreateLogger();
|
|
|
|
#region 废弃-输出Json格式的日志
|
|
//如果有反向代理并不会获取到用户的真实IP
|
|
//.Enrich.WithClientIp()
|
|
//.Enrich.WithRequestHeader("User-Agent")
|
|
//https://github.com/serilog/serilog-formatting-compact
|
|
//// 控制台输出 JSON 格式
|
|
//.WriteTo.Console(formatter: new CompactJsonFormatter(), LogEventLevel.Warning),
|
|
//// 文件输出 JSON 格式
|
|
//.WriteTo.File(new CompactJsonFormatter(), $"{AppContext.BaseDirectory}Serilogs/.json", rollingInterval: RollingInterval.Day);
|
|
#endregion
|
|
|
|
}
|
|
|
|
}
|
|
}
|