serilog 增加环境发生错误发送邮件
continuous-integration/drone/push Build is passing Details

IRC_NewDev
hang 2024-10-22 09:57:25 +08:00
parent 9b91472186
commit f6252f62c4
11 changed files with 67 additions and 48 deletions

View File

@ -77,6 +77,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.10" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Email" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.9.0" />
</ItemGroup>

View File

@ -47,6 +47,9 @@ if (string.IsNullOrWhiteSpace(enviromentName))
}
#endregion
// Serilog
SerilogExtension.AddSerilogSetup(enviromentName);
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
EnvironmentName = enviromentName
@ -131,8 +134,6 @@ builder.Services.AddDicomSetup();
builder.Services.AddSignalR();
//// 添加反伪造服务
//builder.Services.AddAntiforgery(options =>
//{
@ -242,10 +243,6 @@ app.MapHealthChecks("/health");
// Serilog
SerilogExtension.AddSerilogSetup(enviromentName, app.Services);
try

View File

@ -1,17 +1,22 @@
using DocumentFormat.OpenXml.Bibliography;
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.Sinks.Email;
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, IServiceProvider serviceProvider)
public static void AddSerilogSetup(string environment)
{
var config = new LoggerConfiguration()
@ -23,49 +28,48 @@ namespace IRaCIS.Core.API
.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Warning)
.MinimumLevel.Override("Hangfire", LogEventLevel.Warning)
//如果有反向代理并不会获取到用户的真实IP
//.Enrich.WithClientIp()
//.Enrich.WithRequestHeader("User-Agent")
.Enrich.FromLogContext()
.Filter.ByExcluding(logEvent => logEvent.Properties.ContainsKey("RequestPath") && logEvent.Properties["RequestPath"].ToString().Contains("/health"))
//https://github.com/serilog/serilog-formatting-compact
.WriteTo.Console()
.WriteTo.File($"{AppContext.BaseDirectory}Serilogs/.log", rollingInterval: RollingInterval.Day);
//// 控制台输出 JSON 格式
//.WriteTo.Console(formatter: new CompactJsonFormatter(), LogEventLevel.Warning),
//// 文件输出 JSON 格式
//.WriteTo.File(new CompactJsonFormatter(), $"{AppContext.BaseDirectory}Serilogs/.json", rollingInterval: RollingInterval.Day);
////控制台 方便调试 问题 我们显示记录日志 时 获取上下文的ip 和用户名 用户类型
//.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Warning,
// outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {ClientIp} {SourceContext:l} || {Message} || {Exception} ||end {NewLine}")
#region 根据环境配置是否打开错误发送邮件通知
//.WriteTo.File($"{AppContext.BaseDirectory}Serilogs/.log", rollingInterval: RollingInterval.Day,
// outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {ClientIp} {SourceContext:l} || {Message} || {Exception} ||end {NewLine}");
//读取配置文件
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();
//.WriteTo.MSSqlServer("Data Source=DESKTOP-4TU9A6M;Initial Catalog=CoreFrame;User ID=sa;Password=123456", "logs", autoCreateSqlTable: true, restrictedToMinimumLevel: LogEventLevel.Information)//从左至右四个参数分别是数据库连接字符串、表名、如果表不存在是否创建、最低等级。Serilog会默认创建一些列。
#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
//if (environment == "Production")
//{
// config.WriteTo.Email(new EmailConnectionInfo()
// {
// EmailSubject = "系统警告,请速速查看!",//邮件标题
// FromEmail = "test@extimaging.com",//发件人邮箱
// MailServer = "smtp.qiye.aliyun.com",//smtp服务器地址
// NetworkCredentials = new NetworkCredential("test@extimaging.com", "SHzyyl2021"),//两个参数分别是发件人邮箱与客户端授权码
// Port = 465,//端口号
// ToEmail = "872297557@qq.com"//收件人
// }, restrictedToMinimumLevel: LogEventLevel.Error,
// outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [ {Level} {ClientIp} {ClientAgent} {TokenUserRealName} {TokenUserType} ] || [path: {RequestPath} arguments: {RequestBody}] {SourceContext:l} || {Message} || {Exception} ||end {NewLine})");
//}
//扩展方法 获取上下文的ip 用户名 用户类型
//Log.Logger = config.Enrich.WithHttpContextInfo(serviceProvider).CreateLogger();
}
}

View File

@ -70,7 +70,9 @@
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗",
"IsEnv_US": false
"IsEnv_US": false,
"IsOpenErrorNoticeEmail": true,
"ErrorNoticeEmailList": [ "872297557@qq.com" ]
},
"SystemPacsConfig": {
"Port": "11113",

View File

@ -91,7 +91,9 @@
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗",
"IsEnv_US": false
"IsEnv_US": false,
"IsOpenErrorNoticeEmail": false,
"ErrorNoticeEmailList": ["872297557@qq.com"]
},
"SystemPacsConfig": {

View File

@ -74,7 +74,9 @@
"CompanyShortName": "Elevate Imaging",
"CompanyShortNameCN": "展影医疗",
"SiteUrl": "https://lili.elevateimaging.ai/login",
"IsEnv_US": true
"IsEnv_US": true,
"IsOpenErrorNoticeEmail": true,
"ErrorNoticeEmailList": [ "872297557@qq.com" ]
},
"SystemPacsConfig": {

View File

@ -82,7 +82,9 @@
"CompanyShortName": "Elevate Imaging",
"CompanyShortNameCN": "展影医疗",
"SiteUrl": "https://lili.test.elevateimaging.ai/login",
"IsEnv_US": true
"IsEnv_US": true,
"IsOpenErrorNoticeEmail": false,
"ErrorNoticeEmailList": [ "872297557@qq.com" ]
},
"SystemPacsConfig": {

View File

@ -86,7 +86,9 @@
"CompanyShortName": "Elevate Imaging",
"CompanyShortNameCN": "展影医疗",
"SiteUrl": "https://lili.test.elevateimaging.ai/login",
"IsEnv_US": true
"IsEnv_US": true,
"IsOpenErrorNoticeEmail": false,
"ErrorNoticeEmailList": [ "872297557@qq.com" ]
},
"SystemPacsConfig": {

View File

@ -87,7 +87,9 @@
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗",
"IsEnv_US": false
"IsEnv_US": false,
"IsOpenErrorNoticeEmail": false,
"ErrorNoticeEmailList": [ "872297557@qq.com" ]
},
"SystemPacsConfig": {

View File

@ -55,6 +55,7 @@ public class ProjectExceptionFilter(ILogger<ProjectExceptionFilter> _logger, ISt
var errorInfo = $"Exception: {exception.Message}[{exception.StackTrace}]" + (exception.InnerException != null ? $" InnerException: {exception.InnerException.Message}[{exception.InnerException.StackTrace}]" : "");
_logger.LogError(errorInfo);
//_logger.LogError(exception, exception.Message);

View File

@ -63,6 +63,10 @@ public class SystemEmailSendConfig
public string CompanyShortNameCN { get; set; } = string.Empty;
public bool IsEnv_US { get; set; }
public bool IsOpenErrorNoticeEmail { get; set; }
public List<string> ErrorNoticeEmailList { get; set; } =new List<string>();
}
public class SystemEmailSendConfigView