zhangxiaofeng 3 months ago
commit 2eecb467c4

@ -1,13 +1,13 @@
using Microsoft.AspNetCore.Hosting;
using DS.Module.Core.Log;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using SqlSugar;
using System.Text;
using System.Text.RegularExpressions;
using DS.Module.Core.Log;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace DS.Module.Core.Filters;

@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
namespace DS.WMS.JobService
{
public sealed class ArgumentExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
httpContext.RequestServices.GetRequiredService<ILogger<ArgumentExceptionHandler>>()
.LogError(exception, "Exception handled");
if (exception is not ArgumentException) return false;
httpContext.Response.StatusCode = 400;
await httpContext.Response.WriteAsJsonAsync(new
{
exception.Message
}, cancellationToken);
return true;
}
}
}

@ -0,0 +1,128 @@
using DS.Module.Core.Log;
using DS.Module.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DS.WMS.JobService
{
/// <summary>
/// 全局异常错误日志
/// </summary>
public class GlobalExceptionsFilter : IExceptionFilter
{
private readonly IHostingEnvironment _env;
private readonly IServiceProvider _serviceProvider;
public GlobalExceptionsFilter(IHostingEnvironment env, IServiceProvider serviceProvider)
{
_env = env;
_serviceProvider = serviceProvider;
}
public void OnException(ExceptionContext context)
{
var json = new JsonErrorResponse();
json.Message = context.Exception.Message; //错误信息
if (_env.IsDevelopment())
{
json.DevelopmentMessage = context.Exception.StackTrace; //堆栈信息
}
var result = DataResult<Object>.Failed(json.Message);
var objectResult = new BadRequestObjectResult(result);
objectResult.StatusCode = (int?)StatusCodes.Status200OK;
context.Result = objectResult;
// context.Result = new InternalServerErrorObjectResult(json);
//MiniProfiler.Current.CustomTiming("Errors", json.Message);
//记录异常到日志
StringBuilder exMsg = new();
exMsg.AppendLine($"【异常方法:】{context.HttpContext.Request.Path}");
exMsg.AppendLine($"【请求类型:】{context.HttpContext.Request.Method}");
exMsg.AppendLine($"【异常错误:】{context.Exception.Message}");
exMsg.AppendLine($"【堆栈跟踪:】{context.Exception.StackTrace}");
#region 写入日志库
var className = context.Exception.TargetSite.DeclaringType?.FullName;
var groupCollection = Regex.Match(className, "<(.*?)>").Groups;
var methodName = "";
if (groupCollection.Count > 1)
{
methodName = groupCollection[1].Value;
}
var exLog = new SysLogException()
{
ClassName = className,
MethodName = methodName,
ExceptionName = context.Exception.Message,
ExceptionMsg = context.Exception.Message,
ExceptionSource = context.Exception.Source,
StackTrace = context.Exception.StackTrace,
ParamsObj = context.Exception.TargetSite.GetParameters().ToString(),
};
#endregion
// Logger.Log(NLog.LogLevel.Info, "异常信息:" + JsonConvert.SerializeObject(context.Exception));
//采用log4net 进行错误日志记录
//_loggerHelper.Error(json.Message, WriteLog(json.Message, context.Exception));
//_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
}
/// <summary>
/// 自定义返回格式
/// </summary>
/// <param name="throwMsg"></param>
/// <param name="ex"></param>
/// <returns></returns>
public string WriteLog(string throwMsg, Exception ex)
{
return string.Format("【自定义错误】:{0} \r\n【异常类型】{1} \r\n【异常信息】{2} \r\n【堆栈调用】{3}", new object[]
{
throwMsg,
ex.GetType().Name, ex.Message, ex.StackTrace
});
}
}
/// <summary>
///
/// </summary>
public class InternalServerErrorObjectResult : ObjectResult
{
public InternalServerErrorObjectResult(object value) : base(value)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
}
/// <summary>
/// 返回错误信息
/// </summary>
public class JsonErrorResponse
{
/// <summary>
/// 生产环境的消息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 开发环境的消息
/// </summary>
public string DevelopmentMessage { get; set; }
}
}

@ -11,6 +11,7 @@ using DS.WMS.Core.HangfireJob.Interface;
using DS.WMS.Core.HangfireJob.Method;
var builder = Host.CreateApplicationBuilder(args);
var environment = builder.Environment.EnvironmentName;
Console.WriteLine("当前开发环境:" + environment);
//注册配置
@ -23,16 +24,24 @@ builder.Configuration.AddEnvironmentVariables();
//Autofac注入
builder.ConfigureContainer(new AutofacServiceProviderFactory(), builder => builder.RegisterModule(new AutofacModuleRegister()));
builder.Services.AddExceptionHandler<ArgumentExceptionHandler>(); //全局异常
builder.Services.AddUserModuleInstall(); //用户服务
builder.Services.AddRedisModuleInstall();//redis
builder.Services.AddSqlSugarInstall();
builder.Services.AddSaasDbInstall();//分库服务
//注入hangfire
builder.Services.AddWorkServiceHangfireModuleInstall();
builder.Services.AddWindowsService();
builder.Services.AddHostedService<Worker>();
//允许 BackgroundService 中存在未经处理的异常,不停止主机
builder.Services.Configure<HostOptions>(hostOptions =>
{
hostOptions.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
});
//应用作为 Windows 服务
builder.Services.AddWindowsService();
var host = builder.Build();
host.Run();

@ -10,18 +10,7 @@ namespace DS.WMS.JobService
private BackgroundJobServer _server;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
//using (new BackgroundJobServer())
//{
// new BackgroundJobServerOptions()
// {
// Queues = new[] { "op", "task" }
// };
//}
//Hangfire.GlobalConfiguration.Configuration.UseStorage(new MySqlStorage(AppSetting.app(new string[] { "HangfireSettings", "DbString" })));
//. UseMySqlStorage(AppSetting.app(new string[] { "HangfireSettings", "DbString" }));
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@ -32,22 +21,21 @@ namespace DS.WMS.JobService
ServerName = "WorkService",
Queues = new[] { "op", "task" }
};
_server = new BackgroundJobServer(options);
while (!stoppingToken.IsCancellationRequested)
{
//using (var server = new BackgroundJobServer())
//{
// new BackgroundJobServerOptions()
// {
// ServerName = "WorkService",
// Queues = new[] { "op", "task" }
// };
Console.WriteLine("Hangfire Server started. Press any key to exit...");
Console.ReadKey();
//}
try
{
_server = new BackgroundJobServer(options);
Console.WriteLine("Hangfire Server started. Press any key to exit...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex);
await Task.Delay(1000);
}
}
}
}
}

Loading…
Cancel
Save