diff --git a/Admin.NET/Admin.NET.Core/Service/Job/JobMonitor.cs b/Admin.NET/Admin.NET.Core/Service/Job/JobMonitor.cs index 318cade9..d03deeee 100644 --- a/Admin.NET/Admin.NET.Core/Service/Job/JobMonitor.cs +++ b/Admin.NET/Admin.NET.Core/Service/Job/JobMonitor.cs @@ -13,12 +13,14 @@ public class JobMonitor : IJobMonitor { private readonly IEventPublisher _eventPublisher; private readonly SysConfigService _sysConfigService; + private readonly ILogger _logger; public JobMonitor(IServiceScopeFactory scopeFactory) { var serviceScope = scopeFactory.CreateScope(); _sysConfigService = serviceScope.ServiceProvider.GetRequiredService(); - _eventPublisher = serviceScope.ServiceProvider.GetRequiredService(); ; + _eventPublisher = serviceScope.ServiceProvider.GetRequiredService(); + _logger = serviceScope.ServiceProvider.GetRequiredService>(); ; } 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(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(ConfigConst.SysErrorMail)) + { + // 将异常作业发送到邮件 + await _eventPublisher.PublishAsync(CommonConst.SendErrorMail, errorInfo, stoppingToken); + } + else + { + //将异常信息存储本地记录 + _logger.LogError(errorInfo); + } } } } \ No newline at end of file diff --git a/Admin.NET/Admin.NET.Web.Core/Startup.cs b/Admin.NET/Admin.NET.Web.Core/Startup.cs index 933be7e4..73712152 100644 --- a/Admin.NET/Admin.NET.Web.Core/Startup.cs +++ b/Admin.NET/Admin.NET.Web.Core/Startup.cs @@ -80,6 +80,12 @@ public class Startup : AppStartup { options.AddPersistence(); // 添加作业持久化器 options.AddMonitor(); // 添加作业执行监视器 + // 定义未捕获的异常,通常是 Task 异常 + options.UnobservedTaskExceptionHandler = (obj, args) => + { + if (args.Exception?.Message != null) + Log.Error($"JobSchedule 有未处理异常 :{args.Exception?.Message} ", args.Exception); + }; } }); // 脱敏检测