fix:解决定时任务监听到异常时,且配置不发送邮件,本地Log能记录到异常信息

This commit is contained in:
huangye 2024-12-24 16:01:48 +08:00
parent ae6e183054
commit fc09e93014

View File

@ -13,12 +13,14 @@ public class JobMonitor : IJobMonitor
{
private readonly IEventPublisher _eventPublisher;
private readonly SysConfigService _sysConfigService;
private readonly ILogger<JobMonitor> _logger;
public JobMonitor(IServiceScopeFactory scopeFactory)
{
var serviceScope = scopeFactory.CreateScope();
_sysConfigService = serviceScope.ServiceProvider.GetRequiredService<SysConfigService>();
_eventPublisher = serviceScope.ServiceProvider.GetRequiredService<IEventPublisher>(); ;
_eventPublisher = serviceScope.ServiceProvider.GetRequiredService<IEventPublisher>();
_logger = serviceScope.ServiceProvider.GetRequiredService<ILogger<JobMonitor>>(); ;
}
public Task OnExecutingAsync(JobExecutingContext context, CancellationToken stoppingToken)
@ -28,11 +30,19 @@ public class JobMonitor : IJobMonitor
public async Task OnExecutedAsync(JobExecutedContext context, CancellationToken stoppingToken)
{
// 将异常作业发送到邮件
if (await _sysConfigService.GetConfigValueByCode<bool>(ConfigConst.SysErrorMail) && context.Exception != null)
if (context.Exception != null)
{
var errorInfo = $"【{context.Trigger.Description}】定时任务错误:{context.Exception}";
await _eventPublisher.PublishAsync(CommonConst.SendErrorMail, errorInfo, stoppingToken);
if (await _sysConfigService.GetConfigValueByCode<bool>(ConfigConst.SysErrorMail))
{
// 将异常作业发送到邮件
await _eventPublisher.PublishAsync(CommonConst.SendErrorMail, errorInfo, stoppingToken);
}
else
{
//将异常信息存储本地记录
_logger.LogError(errorInfo);
}
}
}
}