diff --git a/Directory.Build.props b/Directory.Build.props index 6bdeda8b..a820b753 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 8.0.2 + 8.0.5.7 diff --git a/src/TrackCenter.Api/ExceptionNotifier.cs b/src/TrackCenter.Api/ExceptionNotifier.cs deleted file mode 100644 index 4f7125d6..00000000 --- a/src/TrackCenter.Api/ExceptionNotifier.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Fake.DependencyInjection; -using Fake.ExceptionHandling; -using TrackCenter.Domain.Extensions; - -namespace TrackCenter.Api; - -public class ExceptionNotifier: IExceptionNotifier, ITransientDependency -{ - public Task NotifyAsync(ExceptionNotificationContext context) - { - LogHelper.Error(context.Exception.ToString()); - - return Task.CompletedTask; - } -} diff --git a/src/TrackCenter.Api/Program.cs b/src/TrackCenter.Api/Program.cs index 6391db20..f63d2ca0 100644 --- a/src/TrackCenter.Api/Program.cs +++ b/src/TrackCenter.Api/Program.cs @@ -2,6 +2,7 @@ using Serilog; using TrackCenter.Api; var builder = WebApplication.CreateSlimBuilder(args); +builder.Configuration.AddConsul("idwms/common", source => source.ReloadOnChange = true); builder.Configuration.AddConsul("idwms/trackapi", source => source.ReloadOnChange = true); var configuration = builder.Configuration; Log.Logger = new LoggerConfiguration() diff --git a/src/TrackCenter.Api/TrackCenter.Api.csproj b/src/TrackCenter.Api/TrackCenter.Api.csproj index 91527b7e..8a522f5e 100644 --- a/src/TrackCenter.Api/TrackCenter.Api.csproj +++ b/src/TrackCenter.Api/TrackCenter.Api.csproj @@ -12,7 +12,6 @@ - @@ -20,9 +19,8 @@ - - - + + diff --git a/src/TrackCenter.Api/TrackCenterApiModule.cs b/src/TrackCenter.Api/TrackCenterApiModule.cs index e656ec98..ea9255d3 100644 --- a/src/TrackCenter.Api/TrackCenterApiModule.cs +++ b/src/TrackCenter.Api/TrackCenterApiModule.cs @@ -1,21 +1,20 @@ using Fake.AspNetCore; using Fake.AspNetCore.Auditing; using Fake.AspNetCore.Mvc; -using Fake.AspNetCore.Mvc.Conventions; using Fake.Autofac; +using Fake.FeiShu; using Fake.Modularity; using Fake.Security.Claims; +using Fake.Serilog; using FluentValidation.AspNetCore; using Hangfire; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; -using Microsoft.OpenApi.Models; using OpenTelemetry.Resources; using OpenTelemetry.Trace; using TrackCenter.Application; using TrackCenter.Application.Hangfire; -using TrackCenter.Domain.Extensions; using TrackCenter.Repository; using TrackCenter.Repository.Otel; using TrackCenter.Repository.Otel.Options; @@ -27,6 +26,7 @@ namespace TrackCenter.Api; [DependsOn(typeof(FakeAspNetCoreModule))] [DependsOn(typeof(TrackCenterApplicationModule))] [DependsOn(typeof(TrackCenterRepositoryModule))] +[DependsOn(typeof(FakeSerilogModule))] public class TrackCenterApiModule : FakeModule { private const string DefaultCorsPolicyName = "default"; @@ -169,11 +169,6 @@ public class TrackCenterApiModule : FakeModule Authorization = [new AnonymousHangfireAuthorizationFilter()] }); - LogHelper.Info("Application started", true); - } - - public override void Shutdown(ApplicationShutdownContext context) - { - LogHelper.Info("Application stoped", true); + app.Services.GetRequiredService().Send("Application started"); } } diff --git a/src/TrackCenter.Application/CAP/CAPFilter.cs b/src/TrackCenter.Application/CAP/CAPFilter.cs index afea2283..9e79b526 100644 --- a/src/TrackCenter.Application/CAP/CAPFilter.cs +++ b/src/TrackCenter.Application/CAP/CAPFilter.cs @@ -55,13 +55,13 @@ public class CapFilter : SubscribeFilter if (context.Exception is CapNoRetryException ex) { context.ExceptionHandled = true; - LogHelper.Warn(ex.ToString(), true); + Log.Warning(ex.ToString(), true); } else { // 发飞书,异常继续上抛,进入重试机制 // tips:重试有冷却期(默认4分钟) - LogHelper.Error($"cap-msg-id:{messageId}\n{context.Exception}"); + Log.Error($"cap-msg-id:{messageId}\n{context.Exception}"); } return Task.CompletedTask; diff --git a/src/TrackCenter.Application/CAP/EventHandlers/TrackChangeAfterUpdateOrderEventHandler.cs b/src/TrackCenter.Application/CAP/EventHandlers/TrackChangeAfterUpdateOrderEventHandler.cs index 0122f0fe..0d801fbf 100644 --- a/src/TrackCenter.Application/CAP/EventHandlers/TrackChangeAfterUpdateOrderEventHandler.cs +++ b/src/TrackCenter.Application/CAP/EventHandlers/TrackChangeAfterUpdateOrderEventHandler.cs @@ -6,17 +6,9 @@ using TrackCenter.Domain.Aggregates.OrderAggregate; namespace TrackCenter.Application.CAP.EventHandlers; -public class TrackChangeAfterUpdateOrderEventHandler : ITransientDependency, ICapSubscribe +public class TrackChangeAfterUpdateOrderEventHandler(IOrderRepository orderRepository, IServiceProvider serviceProvider) + : ITransientDependency, ICapSubscribe { - private readonly IOrderRepository _orderRepository; - private readonly IServiceProvider _serviceProvider; - - public TrackChangeAfterUpdateOrderEventHandler(IOrderRepository orderRepository, IServiceProvider serviceProvider) - { - _orderRepository = orderRepository; - _serviceProvider = serviceProvider; - } - [UnitOfWork] [CapSubscribe(GlobalConst.TrackChangeAfterUpdateOrderSubscribe)] public virtual async Task ConsumerAsync(TrackChangeAfterUpdateOrderEvent @event) @@ -25,7 +17,7 @@ public class TrackChangeAfterUpdateOrderEventHandler : ITransientDependency, ICa if (orders.Count == 0) { - LogHelper.Warn($"没有找到订单信息:{@event.OrderIds.JoinAsString(",")},无法更新轨迹信息"); + Log.Warning($"没有找到订单信息:{@event.OrderIds.JoinAsString(",")},无法更新轨迹信息"); return; } @@ -81,7 +73,7 @@ public class TrackChangeAfterUpdateOrderEventHandler : ITransientDependency, ICa updateOrders.Add(order); } - await _orderRepository.UpdateRangeAsync(updateOrders, x => new + await orderRepository.UpdateRangeAsync(updateOrders, x => new { x.IsCompleted, x.LatestTrackStatus, @@ -103,7 +95,7 @@ public class TrackChangeAfterUpdateOrderEventHandler : ITransientDependency, ICa private async Task> GetOrdersAsync(int[] orderIds) { - return await _orderRepository.GetListAsync(order => orderIds.Contains(order.Id), order => new OrderEntity + return await orderRepository.GetListAsync(order => orderIds.Contains(order.Id), order => new OrderEntity { Id = order.Id, // 轨迹 @@ -123,7 +115,7 @@ public class TrackChangeAfterUpdateOrderEventHandler : ITransientDependency, ICa { _ = Task.Run(async () => { - var scope = _serviceProvider.CreateScope(); + var scope = serviceProvider.CreateScope(); try { var handler = scope.ServiceProvider.GetRequiredService(); @@ -131,7 +123,7 @@ public class TrackChangeAfterUpdateOrderEventHandler : ITransientDependency, ICa } catch (Exception ex) { - LogHelper.Error(ex); + Log.Error(ex.ToString()); } finally { diff --git a/src/TrackCenter.Application/CAP/EventHandlers/TrackDeleteEventHandler.cs b/src/TrackCenter.Application/CAP/EventHandlers/TrackDeleteEventHandler.cs index f20ead91..c3531b83 100644 --- a/src/TrackCenter.Application/CAP/EventHandlers/TrackDeleteEventHandler.cs +++ b/src/TrackCenter.Application/CAP/EventHandlers/TrackDeleteEventHandler.cs @@ -78,7 +78,7 @@ public class TrackDeleteEventHandler : ITransientDependency, ICapSubscribe if (codeMaps.Count == 0) { - LogHelper.Warn($"订单跨应用,未配置内容映射,请联系管理员:{@event}", true); + Log.Warning($"订单跨应用,未配置内容映射,请联系管理员:{@event}", true); continue; } @@ -110,7 +110,7 @@ public class TrackDeleteEventHandler : ITransientDependency, ICapSubscribe var dup = @event.Visited.Intersect(@event.OrderIds).ToArray(); if (dup.Any()) { - LogHelper.Warn($"删除轨迹时,发现循环依赖:{dup.JoinAsString(",")}", true); + Log.Warning($"删除轨迹时,发现循环依赖:{dup.JoinAsString(",")}", true); return false; } diff --git a/src/TrackCenter.Application/CAP/EventHandlers/TrackUpsertEventHandler.cs b/src/TrackCenter.Application/CAP/EventHandlers/TrackUpsertEventHandler.cs index 4ef6e459..2244453f 100644 --- a/src/TrackCenter.Application/CAP/EventHandlers/TrackUpsertEventHandler.cs +++ b/src/TrackCenter.Application/CAP/EventHandlers/TrackUpsertEventHandler.cs @@ -122,7 +122,7 @@ public class TrackUpsertEventHandler : ITransientDependency, ICapSubscribe // 系统创建的轨迹不允许修改 if (@event.Visited.IsNullOrEmpty() && @event is { OperationMan: GlobalConst.SystemUser, IsAdd: false }) { - LogHelper.Warn($"系统创建的轨迹不允许被修改:{@event}", true); + Log.Warning($"系统创建的轨迹不允许被修改:{@event}", true); return false; } @@ -131,7 +131,7 @@ public class TrackUpsertEventHandler : ITransientDependency, ICapSubscribe var dup = @event.Visited.Intersect(orderIds).ToArray(); if (dup.Any()) { - LogHelper.Warn($"{(@event.IsAdd ? "添加" : "修改")}轨迹时,发现循环依赖:{dup.JoinAsString(",")}", true); + Log.Warning($"{(@event.IsAdd ? "添加" : "修改")}轨迹时,发现循环依赖:{dup.JoinAsString(",")}", true); return false; } @@ -146,7 +146,7 @@ public class TrackUpsertEventHandler : ITransientDependency, ICapSubscribe if (trackContent == null) { // 找不到轨迹内容,直接结束 - LogHelper.Warn($"找不到轨迹内容:{@event}", true); + Log.Warning($"找不到轨迹内容:{@event}", true); return; } diff --git a/src/TrackCenter.Application/CAP/LoggerExtensions.cs b/src/TrackCenter.Application/CAP/LoggerExtensions.cs index 08662b76..aadf7184 100644 --- a/src/TrackCenter.Application/CAP/LoggerExtensions.cs +++ b/src/TrackCenter.Application/CAP/LoggerExtensions.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using ILogger = Microsoft.Extensions.Logging.ILogger; namespace TrackCenter.Application.CAP; diff --git a/src/TrackCenter.Application/CAP/MySubscribeExecutor.cs b/src/TrackCenter.Application/CAP/MySubscribeExecutor.cs index b5b296f9..a70f1408 100644 --- a/src/TrackCenter.Application/CAP/MySubscribeExecutor.cs +++ b/src/TrackCenter.Application/CAP/MySubscribeExecutor.cs @@ -7,6 +7,7 @@ using DotNetCore.CAP.Messages; using DotNetCore.CAP.Persistence; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using ILogger = Microsoft.Extensions.Logging.ILogger; namespace TrackCenter.Application.CAP; diff --git a/src/TrackCenter.Application/GlobalUsings.cs b/src/TrackCenter.Application/GlobalUsings.cs index f4a105e7..9f0483c4 100644 --- a/src/TrackCenter.Application/GlobalUsings.cs +++ b/src/TrackCenter.Application/GlobalUsings.cs @@ -3,6 +3,7 @@ global using Fake.DependencyInjection; global using TrackCenter.Domain.Consts; global using Microsoft.AspNetCore.Mvc; global using Microsoft.Extensions.DependencyInjection; +global using Serilog; global using TrackCenter.Domain; global using TrackCenter.Domain.Dtos.Common; global using TrackCenter.Domain.Enums; diff --git a/src/TrackCenter.Application/Hangfire/WarningTaskService.cs b/src/TrackCenter.Application/Hangfire/WarningTaskService.cs index d096bea5..18c66281 100644 --- a/src/TrackCenter.Application/Hangfire/WarningTaskService.cs +++ b/src/TrackCenter.Application/Hangfire/WarningTaskService.cs @@ -104,7 +104,7 @@ public class WarningTaskService( } catch (Exception e) { - LogHelper.Error("[CallTrackRetryPushAsync]" + e, true); + Log.Error("[CallTrackRetryPushAsync]" + e, true); throw; } finally diff --git a/src/TrackCenter.Application/HostServices/WarningCalcBackgroundService.cs b/src/TrackCenter.Application/HostServices/WarningCalcBackgroundService.cs index 3e9e3ec1..250fe7ea 100644 --- a/src/TrackCenter.Application/HostServices/WarningCalcBackgroundService.cs +++ b/src/TrackCenter.Application/HostServices/WarningCalcBackgroundService.cs @@ -62,7 +62,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService return; } - LogHelper.Error(e); + Log.Error(e.ToString()); _activity?.SetTag("Exception", e.Message); } finally @@ -140,7 +140,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService { // 被取消不需要增加重试次数 //needRetryMetadata.AddRange(needHandleMessage.Select(x => TrackSignalMetadata.FormMessageOrCreate(x, false, false, error: error))); - LogHelper.Warn($"处理被取消,消息会重新分配到其他Host,影响消息条数[{needHandleMessage.Count}]"); + Log.Warning($"处理被取消,消息会重新分配到其他Host,影响消息条数[{needHandleMessage.Count}]"); throw error; } @@ -163,7 +163,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService if (needRetryMetadata.Count > 0) { _activity?.SetTag("StartPublicRetryMessage", $"[预警计算] 开始重新投递[{needRetryMetadata.Count}]条消息"); - LogHelper.Warn($"[预警计算] 开始重新投递[{needRetryMetadata.Count}]条消息"); + Log.Warning($"[预警计算] 开始重新投递[{needRetryMetadata.Count}]条消息"); var tasks = needRetryMetadata.Select(async metadata => { @@ -175,14 +175,14 @@ public sealed class WarningCalcBackgroundService : BackgroundService var errorReasons = needRetryMetadata.Select(x => x.LastErrorReason).ToHashSet(); var errorMessage = "------------\r\n" + string.Join("\r\n------------\r\n", errorReasons); _activity?.SetTag("EndPublicRetryMessage", $"[预警计算] 已重新投递[{needRetryMetadata.Count}]条消息\r\n{errorMessage}"); - LogHelper.Warn($"[预警计算] 已重新投递[{needRetryMetadata.Count}]条消息\r\n{errorMessage}", true); + Log.Warning($"[预警计算] 已重新投递[{needRetryMetadata.Count}]条消息\r\n{errorMessage}", true); } // 4.进入死信的消息,投入到死信队列,等待人工处理 if (needEnqueueDlxMetadata.Count > 0) { _activity?.SetTag("StartPublicDLXMessage", $"[预警计算] 开始投递死信[{needEnqueueDlxMetadata.Count}]条消息"); - LogHelper.Warn($"[预警计算] 开始投递死信[{needEnqueueDlxMetadata.Count}]条消息"); + Log.Warning($"[预警计算] 开始投递死信[{needEnqueueDlxMetadata.Count}]条消息"); var tasks = needEnqueueDlxMetadata.Select(async metadata => { @@ -200,7 +200,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService var errorReasons = needRetryMetadata.Select(x => x.LastErrorReason).ToHashSet(); var errorMessage = "------------\r\n" + string.Join("\r\n------------\r\n", errorReasons); _activity?.SetTag("StartPublicDLXMessage", $"[预警计算] 已进入死信队列[{needEnqueueDlxMetadata.Count}]条消息\r\n{errorMessage}"); - LogHelper.Warn($"[预警计算] 已进入死信队列[{needEnqueueDlxMetadata.Count}]条消息\r\n{errorMessage}", true); + Log.Warning($"[预警计算] 已进入死信队列[{needEnqueueDlxMetadata.Count}]条消息\r\n{errorMessage}", true); } } @@ -271,7 +271,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService if (ms.Count == 0) return; var reasons = string.Join(",", ms.GroupBy(x => x.LastErrorReason).Select(x => x.Key)); _activity?.SetTag("AggregateNoSupport", reasons); - LogHelper.Error($"预警信号类型不支持:{reasons}"); + Log.Error($"预警信号类型不支持:{reasons}"); } public override void Dispose() diff --git a/src/TrackCenter.Application/Kafka/WarningCalcBackgroundService.cs b/src/TrackCenter.Application/Kafka/WarningCalcBackgroundService.cs index 85e505aa..4af212fd 100644 --- a/src/TrackCenter.Application/Kafka/WarningCalcBackgroundService.cs +++ b/src/TrackCenter.Application/Kafka/WarningCalcBackgroundService.cs @@ -72,7 +72,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService return; } - LogHelper.Error(e); + Log.Error(e.ToString()); _activity?.SetTag("Exception", e.Message); } finally @@ -192,7 +192,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService { // 被取消不需要增加重试次数 //needRetryMetadata.AddRange(needHandleMessage.Select(x => TrackSignalMetadata.FormMessageOrCreate(x, false, false, error: error))); - LogHelper.Warn($"处理被取消,消息会重新分配到其他Host,影响消息条数[{needHandleMessage.Count}]"); + Log.Warning($"处理被取消,消息会重新分配到其他Host,影响消息条数[{needHandleMessage.Count}]"); throw error; } @@ -215,7 +215,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService if (needRetryMetadata.Count > 0) { _activity?.SetTag("StartPublicRetryMessage", $"[预警计算] 开始重新投递[{needRetryMetadata.Count}]条消息"); - LogHelper.Warn($"[预警计算] 开始重新投递[{needRetryMetadata.Count}]条消息"); + Log.Warning($"[预警计算] 开始重新投递[{needRetryMetadata.Count}]条消息"); var tasks = needRetryMetadata.Select(async metadata => { @@ -227,14 +227,14 @@ public sealed class WarningCalcBackgroundService : BackgroundService var errorReasons = needRetryMetadata.Select(x => x.LastErrorReason).ToHashSet(); var errorMessage = "------------\r\n" + string.Join("\r\n------------\r\n", errorReasons); _activity?.SetTag("EndPublicRetryMessage", $"[预警计算] 已重新投递[{needRetryMetadata.Count}]条消息\r\n{errorMessage}"); - LogHelper.Warn($"[预警计算] 已重新投递[{needRetryMetadata.Count}]条消息\r\n{errorMessage}", true); + Log.Warning($"[预警计算] 已重新投递[{needRetryMetadata.Count}]条消息\r\n{errorMessage}", true); } // 4.进入死信的消息,投入到死信队列,等待人工处理 if (needEnqueueDlxMetadata.Count > 0) { _activity?.SetTag("StartPublicDLXMessage", $"[预警计算] 开始投递死信[{needEnqueueDlxMetadata.Count}]条消息"); - LogHelper.Warn($"[预警计算] 开始投递死信[{needEnqueueDlxMetadata.Count}]条消息"); + Log.Warning($"[预警计算] 开始投递死信[{needEnqueueDlxMetadata.Count}]条消息"); var tasks = needEnqueueDlxMetadata.Select(async metadata => { @@ -252,7 +252,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService var errorReasons = needRetryMetadata.Select(x => x.LastErrorReason).ToHashSet(); var errorMessage = "------------\r\n" + string.Join("\r\n------------\r\n", errorReasons); _activity?.SetTag("StartPublicDLXMessage", $"[预警计算] 已进入死信队列[{needEnqueueDlxMetadata.Count}]条消息\r\n{errorMessage}"); - LogHelper.Warn($"[预警计算] 已进入死信队列[{needEnqueueDlxMetadata.Count}]条消息\r\n{errorMessage}", true); + Log.Warning($"[预警计算] 已进入死信队列[{needEnqueueDlxMetadata.Count}]条消息\r\n{errorMessage}", true); } } @@ -323,7 +323,7 @@ public sealed class WarningCalcBackgroundService : BackgroundService if (ms.Count == 0) return; var reasons = string.Join(",", ms.GroupBy(x => x.LastErrorReason).Select(x => x.Key)); _activity?.SetTag("AggregateNoSupport", reasons); - LogHelper.Error($"预警信号类型不支持:{reasons}"); + Log.Error($"预警信号类型不支持:{reasons}"); } public override void Dispose() diff --git a/src/TrackCenter.Application/Kafka/WarningCalcServiceExtension.cs b/src/TrackCenter.Application/Kafka/WarningCalcServiceExtension.cs index 985d4753..b844cdb5 100644 --- a/src/TrackCenter.Application/Kafka/WarningCalcServiceExtension.cs +++ b/src/TrackCenter.Application/Kafka/WarningCalcServiceExtension.cs @@ -64,7 +64,7 @@ public static class WarningCalcServiceExtension { if (error.IsFatal) { - LogHelper.Error($"Kafka致命错误${error}"); + Log.Error($"Kafka致命错误${error}"); return; } @@ -72,9 +72,9 @@ public static class WarningCalcServiceExtension reportFuncWrapper ??= DebounceHelper.WrapMethod(TimeSpan.FromSeconds(5), () => { if (error.Code == ErrorCode.Local_Transport) - LogHelper.Error($"Kafka链接错误{error}"); + Log.Error($"Kafka链接错误{error}"); else if (error.Code == ErrorCode.Local_AllBrokersDown) - LogHelper.Error($"Kafka所有Broker都挂了{error}"); + Log.Error($"Kafka所有Broker都挂了{error}"); }); reportFuncWrapper.Debounce(); }); @@ -124,7 +124,7 @@ public static class WarningCalcServiceExtension { if (error.IsFatal) { - LogHelper.Error($"Kafka致命错误${error}"); + Log.Error($"Kafka致命错误${error}"); return; } @@ -132,9 +132,9 @@ public static class WarningCalcServiceExtension reportFuncWrapper ??= DebounceHelper.WrapMethod(TimeSpan.FromSeconds(5), () => { if (error.Code == ErrorCode.Local_Transport) - LogHelper.Error($"Kafka链接错误{error}"); + Log.Error($"Kafka链接错误{error}"); else if (error.Code == ErrorCode.Local_AllBrokersDown) - LogHelper.Error($"Kafka所有Broker都挂了{error}"); + Log.Error($"Kafka所有Broker都挂了{error}"); }); reportFuncWrapper.Debounce(); }); diff --git a/src/TrackCenter.Application/Rabbit/TrackPushCompletedEventHandler.cs b/src/TrackCenter.Application/Rabbit/TrackPushCompletedEventHandler.cs index 19eebd82..aabd805c 100644 --- a/src/TrackCenter.Application/Rabbit/TrackPushCompletedEventHandler.cs +++ b/src/TrackCenter.Application/Rabbit/TrackPushCompletedEventHandler.cs @@ -44,7 +44,7 @@ public class TrackPushCompletedEventHandler : ITransientDependency, IRabbitHandl var @event = System.Text.Json.JsonSerializer.Deserialize(msg); if (@event == null) { - LogHelper.Warn( + Log.Warning( $"rabbit on queue received msg can't convert to {nameof(InterfaceRelayForwardReplayEvent)}"); return; } @@ -53,7 +53,7 @@ public class TrackPushCompletedEventHandler : ITransientDependency, IRabbitHandl } catch (Exception ex) { - LogHelper.Error($"TrackPushCompletedEventHandler出错,错误信息:{ex}\r\n-----\r\n消息:{msg}"); + Log.Error($"TrackPushCompletedEventHandler出错,错误信息:{ex}\r\n-----\r\n消息:{msg}"); } } diff --git a/src/TrackCenter.Application/Rabbit/TrackRefreshEventHandler.cs b/src/TrackCenter.Application/Rabbit/TrackRefreshEventHandler.cs index 28b78a05..83cfc202 100644 --- a/src/TrackCenter.Application/Rabbit/TrackRefreshEventHandler.cs +++ b/src/TrackCenter.Application/Rabbit/TrackRefreshEventHandler.cs @@ -52,7 +52,7 @@ public class TrackRefreshEventHandler( } catch (Exception ex) { - LogHelper.Error($"TrackRefreshEventHandler出错,错误信息:{ex}\r\n-----\r\n消息:{msg}"); + Log.Error($"TrackRefreshEventHandler出错,错误信息:{ex}\r\n-----\r\n消息:{msg}"); } } diff --git a/src/TrackCenter.Application/Services/DebugApis/_EsInitService.cs b/src/TrackCenter.Application/Services/DebugApis/_EsInitService.cs index 11906335..8291caa2 100644 --- a/src/TrackCenter.Application/Services/DebugApis/_EsInitService.cs +++ b/src/TrackCenter.Application/Services/DebugApis/_EsInitService.cs @@ -12,9 +12,9 @@ public class _EsInitService( [HttpGet("EsInit")] public async Task EsInit() { - LogHelper.Warn($"ES索引初始化开始 OperationUserId:[{CurrentUser.Id}]", true); + Log.Warning($"ES索引初始化开始 OperationUserId:[{CurrentUser.Id}]", true); await trackDetailsEsRepository.MigrateAsync(); await warningDetailsEsRepository.CreateAliasAsync(); - LogHelper.Warn($"ES索引初始化完成 OperationUserId:[{CurrentUser.Id}]", true); + Log.Warning($"ES索引初始化完成 OperationUserId:[{CurrentUser.Id}]", true); } } diff --git a/src/TrackCenter.Application/Services/ProvideServices/OrderService.PullConfigs.cs b/src/TrackCenter.Application/Services/ProvideServices/OrderService.PullConfigs.cs index 0d102499..4237f8c5 100644 --- a/src/TrackCenter.Application/Services/ProvideServices/OrderService.PullConfigs.cs +++ b/src/TrackCenter.Application/Services/ProvideServices/OrderService.PullConfigs.cs @@ -23,7 +23,7 @@ public partial class OrderService inputVo.OrderIds = orderIds.ToArray(); var cnt = await _orderRepository.UpdateOrderPullConfigForServiceProviderAsync(inputVo); - LogHelper.Warn( + Log.Warning( $"{CurrentUser.UserName}正在修改服务商拉取信息,本次共计影响了{orderIds.Count}个订单、{cnt}段拉取,请求参数是:{input.ToJson()}", true); } diff --git a/src/TrackCenter.Application/Services/ProvideServices/OrderService.cs b/src/TrackCenter.Application/Services/ProvideServices/OrderService.cs index c16c796b..870f6999 100644 --- a/src/TrackCenter.Application/Services/ProvideServices/OrderService.cs +++ b/src/TrackCenter.Application/Services/ProvideServices/OrderService.cs @@ -273,7 +273,7 @@ public partial class OrderService : ApplicationServiceBase } catch (Exception ex) { - LogHelper.Error(ex); + Log.Error(ex.ToString()); } finally { diff --git a/src/TrackCenter.Application/Services/ProvideServices/TrackPullService.cs b/src/TrackCenter.Application/Services/ProvideServices/TrackPullService.cs index 82582e8c..87e185e4 100644 --- a/src/TrackCenter.Application/Services/ProvideServices/TrackPullService.cs +++ b/src/TrackCenter.Application/Services/ProvideServices/TrackPullService.cs @@ -79,7 +79,7 @@ public class TrackPullService : ApplicationServiceBase if (res.Code != GlobalConst.SuccessCode) { - LogHelper.Error($"刷新轨迹失败:{res.ToJson()}"); + Log.Error($"刷新轨迹失败:{res.ToJson()}"); } } } diff --git a/src/TrackCenter.Application/Services/ProvideServices/TrackPushService.cs b/src/TrackCenter.Application/Services/ProvideServices/TrackPushService.cs index 962f53b7..7d24e23e 100644 --- a/src/TrackCenter.Application/Services/ProvideServices/TrackPushService.cs +++ b/src/TrackCenter.Application/Services/ProvideServices/TrackPushService.cs @@ -139,7 +139,7 @@ public class TrackPushService : ApplicationServiceBase await _capPublisher.PublishAsync(GlobalConst.TrackManualPushSubscribe, trackPushEvent); } - LogHelper.Info($"即将推送轨迹代码{input.TrackCode}给{orderIdTrackDict.Count}个订单"); + Log.Information($"即将推送轨迹代码{input.TrackCode}给{orderIdTrackDict.Count}个订单"); } diff --git a/src/TrackCenter.Application/Services/TimerTaskss/OrderPullStatusScanTask.cs b/src/TrackCenter.Application/Services/TimerTaskss/OrderPullStatusScanTask.cs index 4eae04d8..31c6b41a 100644 --- a/src/TrackCenter.Application/Services/TimerTaskss/OrderPullStatusScanTask.cs +++ b/src/TrackCenter.Application/Services/TimerTaskss/OrderPullStatusScanTask.cs @@ -56,7 +56,7 @@ public class OrderPullStatusScanTask : ApplicationServiceBase catch (Exception e) { await RedisHelper.Client.DelAsync(redisKey); - LogHelper.Error(e.ToString()); + Log.Error(e.ToString()); } diff --git a/src/TrackCenter.Application/Services/TimerTaskss/TrackButtomUpScanTask.cs b/src/TrackCenter.Application/Services/TimerTaskss/TrackButtomUpScanTask.cs index 03c63277..164dca57 100644 --- a/src/TrackCenter.Application/Services/TimerTaskss/TrackButtomUpScanTask.cs +++ b/src/TrackCenter.Application/Services/TimerTaskss/TrackButtomUpScanTask.cs @@ -48,7 +48,7 @@ public class TrackButtomUpScanTask : ApplicationServiceBase catch (Exception e) { await RedisHelper.Client.DelAsync(redisKey); - LogHelper.Error(e.ToString()); + Log.Error(e.ToString()); } return "ok"; diff --git a/src/TrackCenter.Application/Services/TimerTaskss/TrackPullTask.cs b/src/TrackCenter.Application/Services/TimerTaskss/TrackPullTask.cs index 250ca2b5..8bdb0f1f 100644 --- a/src/TrackCenter.Application/Services/TimerTaskss/TrackPullTask.cs +++ b/src/TrackCenter.Application/Services/TimerTaskss/TrackPullTask.cs @@ -84,7 +84,7 @@ public class TrackPullTask : ApplicationServiceBase, ISingletonDependency catch (Exception e) { await RedisHelper.Client.DelAsync(redisKey); - LogHelper.Error(e.ToString()); + Log.Error(e.ToString()); } }); } @@ -116,7 +116,7 @@ public class TrackPullTask : ApplicationServiceBase, ISingletonDependency if (res.Code != GlobalConst.SuccessCode) { - LogHelper.Error($"刷新轨迹失败:{res.ToJson()}"); + Log.Error($"刷新轨迹失败:{res.ToJson()}"); } } diff --git a/src/TrackCenter.Application/Services/TimerTaskss/TrackPushTask.cs b/src/TrackCenter.Application/Services/TimerTaskss/TrackPushTask.cs index 164b61a6..591b824e 100644 --- a/src/TrackCenter.Application/Services/TimerTaskss/TrackPushTask.cs +++ b/src/TrackCenter.Application/Services/TimerTaskss/TrackPushTask.cs @@ -59,7 +59,7 @@ public class TrackPushTask : ApplicationServiceBase catch (Exception e) { await RedisHelper.Client.DelAsync(redisKey); - LogHelper.Error(e.ToString()); + Log.Error(e.ToString()); } }); } @@ -78,6 +78,6 @@ public class TrackPushTask : ApplicationServiceBase await Task.Delay(waitTime); } while (rows == pageSize); - LogHelper.Info($"本次预警扫描了:{total}个订单"); + Log.Information($"本次预警扫描了:{total}个订单"); } } diff --git a/src/TrackCenter.Application/Services/TrackOrders/TrackOrderService.cs b/src/TrackCenter.Application/Services/TrackOrders/TrackOrderService.cs index 6a502ae6..ec08f3bf 100644 --- a/src/TrackCenter.Application/Services/TrackOrders/TrackOrderService.cs +++ b/src/TrackCenter.Application/Services/TrackOrders/TrackOrderService.cs @@ -333,7 +333,7 @@ public class TrackOrderService : ApplicationServiceBase } catch (Exception ex) { - LogHelper.Error(ex); + Log.Error(ex.ToString()); } finally { diff --git a/src/TrackCenter.Application/Services/TrackPush/TrackPushService.cs b/src/TrackCenter.Application/Services/TrackPush/TrackPushService.cs index 06e40a4d..fa6dd817 100644 --- a/src/TrackCenter.Application/Services/TrackPush/TrackPushService.cs +++ b/src/TrackCenter.Application/Services/TrackPush/TrackPushService.cs @@ -291,7 +291,7 @@ public class TrackPushService( } catch (Exception ex) { - LogHelper.Error(ex); + Log.Error(ex.ToString()); } finally { diff --git a/src/TrackCenter.Application/Track2InterfaceRelay/InterfaceForwardService.cs b/src/TrackCenter.Application/Track2InterfaceRelay/InterfaceForwardService.cs index 523d90a6..5018fab7 100644 --- a/src/TrackCenter.Application/Track2InterfaceRelay/InterfaceForwardService.cs +++ b/src/TrackCenter.Application/Track2InterfaceRelay/InterfaceForwardService.cs @@ -50,7 +50,7 @@ public class InterfaceForwardService : ITransientDependency content.Headers.Add(nameof(other), other); content.Headers.Add(nameof(sourceData), sourceData.ToString()); - using var response = await client.PostAsync($"Itfx/BatchRequest?standardCode={upStreamCode}&supplierCode={serviceProviderCode}", content); + using var response = await client.PostAsync($"InterfaceForward/BatchRequest?standardCode={upStreamCode}&supplierCode={serviceProviderCode}", content); var res = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) diff --git a/src/TrackCenter.Application/TrackCenterApplicationModule.cs b/src/TrackCenter.Application/TrackCenterApplicationModule.cs index 6556d9d3..b01ebbb3 100644 --- a/src/TrackCenter.Application/TrackCenterApplicationModule.cs +++ b/src/TrackCenter.Application/TrackCenterApplicationModule.cs @@ -15,6 +15,7 @@ using Hangfire.Redis.StackExchange; using InterfaceForward.Domain.Shared.Helpers; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Logging; using RabbitMQ.Client; using Savorboard.CAP.InMemoryMessageQueue; using TrackCenter.Application.Kafka; @@ -74,14 +75,14 @@ public class TrackCenterApplicationModule : FakeModule { try { - LogHelper.Error($@" + Log.Error($@" |-CAP失败回调事件: |-处理类型:{(faileCalback.MessageType == MessageType.Subscribe ? "消费消息达到最大重试次数,需要开发人员介入" : "生产消息推送失败")} |-头部信息:{faileCalback.Message.Headers.ToJson()}"); } catch (Exception ex) { - LogHelper.Error("【严重】CAP失败回调事件发生未处理异常" + ex); + Log.Error("【严重】CAP失败回调事件发生未处理异常" + ex); } }; }).AddSubscribeFilter(); @@ -95,7 +96,7 @@ public class TrackCenterApplicationModule : FakeModule capOptions.UseInMemoryMessageQueue(); capOptions.UseDashboard(); }).AddSubscribeFilter(); - LogHelper.Info("-- 当前为本地环境,用内存存储和内存队列"); + Log.Information("-- 当前为本地环境,用内存存储和内存队列"); } #endregion diff --git a/src/TrackCenter.Domain/Extensions/LogHelper.cs b/src/TrackCenter.Domain/Extensions/LogHelper.cs deleted file mode 100644 index 7190c140..00000000 --- a/src/TrackCenter.Domain/Extensions/LogHelper.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System.Net.Http.Headers; -using System.Text; -using System.Text.Json; -using Fake.SyncEx; -using Serilog; - -namespace TrackCenter.Domain.Extensions; - -public static class LogHelper -{ - private static FeiShuNoticeOptions _options = null!; - - public static void Init(FeiShuNoticeOptions options) - { - _options = options; - } - public static void Info(string msg, bool isSend = false) - { - Log.Information(msg); - if (!isSend) - return; - SyncContext.Run(() => NoticeAsync(msg, isSend, "Info")); - } - - public static void Warn(string msg, bool isSend = false) - { - Log.Warning(msg); - if (!isSend) - return; - SyncContext.Run(() => NoticeAsync(msg, isSend, "Warn")); - } - - public static void Error(string msg, bool isSend = true) - { - Log.Error(msg); - SyncContext.Run(() => NoticeAsync(msg, isSend, "Error")); - } - - public static void Error(Exception error, bool isSendNotice = true) - { - Error(error.ToString(), isSendNotice); - } - - - public static async Task NoticeAsync(string content, bool isSend, string subTitle = "") - { -#if DEBUG - // 调试模式下不发送通知 - return; -#endif - if (!isSend) - { - return; - } - - if (_options.Webhook.IsNullOrWhiteSpace()) - { - Log.Warning("未配置飞书webhook"); - return; - } - - var title = subTitle.IsNullOrWhiteSpace() - ? _options.TitlePrefix - : _options.TitlePrefix + "_" + subTitle; - - await HandleNoticeAsync(content, title); - } - - private static async Task HandleNoticeAsync(string content, string title) - { - var message = new - { - msg_type = "post", - content = new - { - post = new - { - zh_cn = new - { - title, - content = new List() - { - new List() - { - new - { - tag = "text", - text = content + Environment.NewLine - } - } - } - } - } - } - }; - - using var httpClient = new HttpClient(); - httpClient.Timeout = TimeSpan.FromSeconds(_options.Timeout); - using var httpContent = new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8); - httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - await httpClient.PostAsync(_options.Webhook, httpContent); - } -} - -public class FeiShuNoticeOptions -{ - /// - /// 飞书通知webhook - /// - public string Webhook { get; set; } - - /// - /// 消息标题前缀 - /// - public string TitlePrefix { get; set; } - - /// - /// 超时时间 秒 - /// - public int Timeout { get; set; } = 20; -} diff --git a/src/TrackCenter.Domain/TrackCenter.Domain.csproj b/src/TrackCenter.Domain/TrackCenter.Domain.csproj index d8e30d4a..afc194b5 100644 --- a/src/TrackCenter.Domain/TrackCenter.Domain.csproj +++ b/src/TrackCenter.Domain/TrackCenter.Domain.csproj @@ -12,7 +12,7 @@ - + diff --git a/src/TrackCenter.Domain/TrackCenterDomainModule.cs b/src/TrackCenter.Domain/TrackCenterDomainModule.cs index cb8ea79f..5274f690 100644 --- a/src/TrackCenter.Domain/TrackCenterDomainModule.cs +++ b/src/TrackCenter.Domain/TrackCenterDomainModule.cs @@ -11,7 +11,5 @@ public class TrackCenterDomainModule : FakeModule { public override void ConfigureServices(ServiceConfigurationContext context) { - var configuration = context.Services.GetConfiguration(); - LogHelper.Init(configuration.GetSection("FeiShuNotice").Get()!); } } diff --git a/src/TrackCenter.Repository/ES/ConnectionFactory.cs b/src/TrackCenter.Repository/ES/ConnectionFactory.cs index eb51b82b..b0a42755 100644 --- a/src/TrackCenter.Repository/ES/ConnectionFactory.cs +++ b/src/TrackCenter.Repository/ES/ConnectionFactory.cs @@ -5,8 +5,6 @@ using Elasticsearch.Net; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Nest; -using Serilog; -using TrackCenter.Domain.Extensions; namespace TrackCenter.Repository.ES; @@ -67,7 +65,7 @@ public class ConnectionFactory : ISingletonDependency .OnRequestCompleted(apiCallDetails => { var infos = GetInfosFromApiCallDetails(apiCallDetails); - LogHelper.Info($"{Environment.NewLine}{infos}{Environment.NewLine}"); + Console.WriteLine($"{Environment.NewLine}{infos}{Environment.NewLine}"); })); } else diff --git a/src/TrackCenter.Repository/Repositories/OrderOperationRecordEsRepository.cs b/src/TrackCenter.Repository/Repositories/OrderOperationRecordEsRepository.cs index 6807a49a..50332507 100644 --- a/src/TrackCenter.Repository/Repositories/OrderOperationRecordEsRepository.cs +++ b/src/TrackCenter.Repository/Repositories/OrderOperationRecordEsRepository.cs @@ -1,9 +1,10 @@ +using Fake.FeiShu; using Nest; using TrackCenter.Domain.Aggregates.OrderAggregate; using TrackCenter.Domain.Consts; -using TrackCenter.Domain.Extensions; using TrackCenter.Repository.Aggregates.OrderAggregate; using TrackCenter.Repository.ES; +using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace TrackCenter.Repository.Repositories; @@ -11,8 +12,11 @@ public class OrderOperationRecordEsRepository : ElasticSearchContextAbstract, IOrderRepository, ITransientDependency { + private readonly IFeiShuNotificationService _feiShuNotification; + + public OrderRepository(IFeiShuNotificationService feiShuNotification) + { + _feiShuNotification = feiShuNotification; + } public async Task> GetTrackOrderPagedList(GetPageTrackOrderInputVO input) { //查询完去重 @@ -474,15 +481,13 @@ public class OrderRepository : BasicRepository, IOrderRepository, I .SetColumns(x => x.PullStatus == TrackPullStatus.Pulling) .Where(x => x.PullStatus == TrackPullStatus.SilenceBeforeStart && x.StartTime < DateTime.Now) .ExecuteCommandAsync(); - LogHelper.Info( - $"{cnt1}条订单的拉取状态由{nameof(TrackPullStatus.SilenceBeforeStart)}更新为{nameof(TrackPullStatus.Pulling)}"); + _feiShuNotification.Enqueue($"{cnt1}条订单的拉取状态由{nameof(TrackPullStatus.SilenceBeforeStart)}更新为{nameof(TrackPullStatus.Pulling)}", LogLevel.Error); var cnt2 = await Context.Updateable() .SetColumns(x => x.PullStatus == TrackPullStatus.Completed) .Where(x => x.PullStatus == TrackPullStatus.SilenceAfterEnd && x.EndTime < DateTime.Now) .ExecuteCommandAsync(); - LogHelper.Info( - $"{cnt2}条订单的拉取状态由{nameof(TrackPullStatus.SilenceAfterEnd)}更新为{nameof(TrackPullStatus.Completed)}"); + _feiShuNotification.Enqueue($"{cnt2}条订单的拉取状态由{nameof(TrackPullStatus.SilenceAfterEnd)}更新为{nameof(TrackPullStatus.Completed)}", LogLevel.Error); return cnt1 + cnt2; } diff --git a/src/TrackCenter.Repository/Repositories/TrackPushRecordEsRepository.cs b/src/TrackCenter.Repository/Repositories/TrackPushRecordEsRepository.cs index fdfed74d..1424e571 100644 --- a/src/TrackCenter.Repository/Repositories/TrackPushRecordEsRepository.cs +++ b/src/TrackCenter.Repository/Repositories/TrackPushRecordEsRepository.cs @@ -1,8 +1,9 @@ +using Fake.FeiShu; using Nest; using TrackCenter.Domain.Aggregates.TrackPushAggregate; using TrackCenter.Domain.Consts; -using TrackCenter.Domain.Extensions; using TrackCenter.Repository.ES; +using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace TrackCenter.Repository.Repositories; @@ -10,8 +11,11 @@ public class TrackPushRecordEsRepository : ElasticSearchContextAbstract