优化全局过滤器日志记录
This commit is contained in:
parent
76c53b9915
commit
314eb40ed9
@ -111,6 +111,11 @@ namespace Infrastructure.Model
|
|||||||
/// <param name="msg"></param>
|
/// <param name="msg"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static ApiResult Error(string msg) { return new ApiResult((int)ResultCode.CUSTOM_ERROR, msg); }
|
public static ApiResult Error(string msg) { return new ApiResult((int)ResultCode.CUSTOM_ERROR, msg); }
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"msg={Msg},data={Data}";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ApiResult<T> : ApiResult
|
public class ApiResult<T> : ApiResult
|
||||||
|
|||||||
@ -12,7 +12,6 @@ using ZR.Admin.WebApi.Filters;
|
|||||||
|
|
||||||
namespace ZR.Admin.WebApi.Controllers
|
namespace ZR.Admin.WebApi.Controllers
|
||||||
{
|
{
|
||||||
[LogActionFilter]
|
|
||||||
public class BaseController : ControllerBase
|
public class BaseController : ControllerBase
|
||||||
{
|
{
|
||||||
public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
|
public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
|
||||||
|
|||||||
@ -6,8 +6,10 @@ using Microsoft.AspNetCore.Http;
|
|||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using UAParser;
|
using UAParser;
|
||||||
@ -161,6 +163,32 @@ namespace ZR.Admin.WebApi.Extensions
|
|||||||
});
|
});
|
||||||
}).Wait();
|
}).Wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置请求参数
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="operLog"></param>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
public static void GetRequestValue(this HttpContext context, SysOperLog operLog)
|
||||||
|
{
|
||||||
|
string reqMethod = operLog.requestMethod;
|
||||||
|
string param;
|
||||||
|
|
||||||
|
if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod))
|
||||||
|
{
|
||||||
|
context.Request.Body.Seek(0, SeekOrigin.Begin);
|
||||||
|
using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
|
||||||
|
//需要使用异步方式才能获取
|
||||||
|
param = reader.ReadToEndAsync().Result;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
param = context.Request.QueryString.Value.ToString();
|
||||||
|
}
|
||||||
|
operLog.operParam = param;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,27 +1,43 @@
|
|||||||
using Infrastructure;
|
using Infrastructure;
|
||||||
|
using Infrastructure.Attribute;
|
||||||
using Infrastructure.Model;
|
using Infrastructure.Model;
|
||||||
|
using IPTools.Core;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||||
using Microsoft.AspNetCore.Mvc.Filters;
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
using NLog;
|
using NLog;
|
||||||
using System;
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using ZR.Admin.WebApi.Extensions;
|
||||||
|
using ZR.Model.System;
|
||||||
|
using ZR.Service.System.IService;
|
||||||
|
|
||||||
namespace ZR.Admin.WebApi.Filters
|
namespace ZR.Admin.WebApi.Filters
|
||||||
{
|
{
|
||||||
public class GlobalActionMonitor : Attribute, IActionFilter
|
public class GlobalActionMonitor : ActionFilterAttribute
|
||||||
{
|
{
|
||||||
static readonly Logger logger = LogManager.GetCurrentClassLogger();
|
static readonly Logger logger = LogManager.GetCurrentClassLogger();
|
||||||
|
private ISysOperLogService OperLogService;
|
||||||
|
public GlobalActionMonitor(ISysOperLogService operLogService)
|
||||||
|
{
|
||||||
|
OperLogService = operLogService;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// OnActionExecuting是在Action执行之前运行的方法。
|
/// Action请求前
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
public void OnActionExecuting(ActionExecutingContext context)
|
/// <param name="next"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||||
{
|
{
|
||||||
if (context.ModelState.IsValid) return;
|
ApiResult response = new();
|
||||||
ApiResult response = new ApiResult();
|
|
||||||
response.Code = (int)ResultCode.PARAM_ERROR;
|
response.Code = (int)ResultCode.PARAM_ERROR;
|
||||||
|
|
||||||
//var keys = context.ModelState.Keys;
|
|
||||||
var values = context.ModelState.Values;
|
var values = context.ModelState.Values;
|
||||||
foreach (var item in values)
|
foreach (var item in values)
|
||||||
{
|
{
|
||||||
@ -29,7 +45,7 @@ namespace ZR.Admin.WebApi.Filters
|
|||||||
{
|
{
|
||||||
if (err.ErrorMessage.Contains("JSON"))
|
if (err.ErrorMessage.Contains("JSON"))
|
||||||
{
|
{
|
||||||
return;
|
return next();
|
||||||
}
|
}
|
||||||
if (!string.IsNullOrEmpty(response.Msg))
|
if (!string.IsNullOrEmpty(response.Msg))
|
||||||
{
|
{
|
||||||
@ -39,16 +55,94 @@ namespace ZR.Admin.WebApi.Filters
|
|||||||
response.Msg += err.ErrorMessage;
|
response.Msg += err.ErrorMessage;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
logger.Info($"请求参数错误,{response.Msg}");
|
if (!string.IsNullOrEmpty(response.Msg))
|
||||||
context.Result = new JsonResult(response);
|
{
|
||||||
|
logger.Info($"请求参数错误,{response.Msg}");
|
||||||
|
context.Result = new JsonResult(response);
|
||||||
|
}
|
||||||
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// OnActionExecuted是在Action中的代码执行之后运行的方法。
|
/// OnActionExecuted是在Action中的代码执行之后运行的方法。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
public void OnActionExecuted(ActionExecutedContext context)
|
public override void OnResultExecuted(ResultExecutedContext context)
|
||||||
{
|
{
|
||||||
|
if (context.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor) return;
|
||||||
|
|
||||||
|
//获得注解信息
|
||||||
|
LogAttribute logAttribute = GetLogAttribute(controllerActionDescriptor);
|
||||||
|
if (logAttribute == null) return;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string method = context.HttpContext.Request.Method.ToUpper();
|
||||||
|
// 获取当前的用户
|
||||||
|
string userName = context.HttpContext.GetName();
|
||||||
|
string jsonResult = string.Empty;
|
||||||
|
if (context.Result is ContentResult result && result.ContentType == "application/json")
|
||||||
|
{
|
||||||
|
jsonResult = result.Content.Replace("\r\n", "").Trim();
|
||||||
|
}
|
||||||
|
if (context.Result is JsonResult result2)
|
||||||
|
{
|
||||||
|
jsonResult = result2.Value?.ToString();
|
||||||
|
}
|
||||||
|
//获取当前执行方法的类名
|
||||||
|
//string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
|
||||||
|
//获取当前成员的名称
|
||||||
|
//string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
|
||||||
|
string controller = context.RouteData.Values["Controller"].ToString();
|
||||||
|
string action = context.RouteData.Values["Action"].ToString();
|
||||||
|
|
||||||
|
string ip = HttpContextExtension.GetClientUserIp(context.HttpContext);
|
||||||
|
var ip_info = IpTool.Search(ip);
|
||||||
|
|
||||||
|
SysOperLog sysOperLog = new()
|
||||||
|
{
|
||||||
|
status = 0,
|
||||||
|
operName = userName,
|
||||||
|
operIp = ip,
|
||||||
|
operUrl = HttpContextExtension.GetRequestUrl(context.HttpContext),
|
||||||
|
requestMethod = method,
|
||||||
|
jsonResult = jsonResult,
|
||||||
|
operLocation = ip_info.Province + " " + ip_info.City,
|
||||||
|
method = controller + "." + action + "()",
|
||||||
|
//Elapsed = _stopwatch.ElapsedMilliseconds,
|
||||||
|
operTime = DateTime.Now
|
||||||
|
};
|
||||||
|
HttpContextExtension.GetRequestValue(context.HttpContext, sysOperLog);
|
||||||
|
|
||||||
|
if (logAttribute != null)
|
||||||
|
{
|
||||||
|
sysOperLog.title = logAttribute?.Title;
|
||||||
|
sysOperLog.businessType = (int)logAttribute?.BusinessType;
|
||||||
|
sysOperLog.operParam = logAttribute.IsSaveRequestData ? sysOperLog.operParam : "";
|
||||||
|
sysOperLog.jsonResult = logAttribute.IsSaveResponseData ? sysOperLog.jsonResult : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
LogEventInfo ei = new(LogLevel.Info, "GlobalExceptionMiddleware", "");
|
||||||
|
ei.Properties["status"] = 0;
|
||||||
|
ei.Properties["jsonResult"] = !HttpMethods.IsGet(method) ? jsonResult : "";
|
||||||
|
ei.Properties["requestParam"] = sysOperLog.operParam;
|
||||||
|
ei.Properties["user"] = userName;
|
||||||
|
logger.Log(ei);
|
||||||
|
|
||||||
|
OperLogService.InsertOperlog(sysOperLog);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, $"记录操作日志出错了#{ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LogAttribute GetLogAttribute(ControllerActionDescriptor controllerActionDescriptor)
|
||||||
|
{
|
||||||
|
var attribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
|
||||||
|
.FirstOrDefault(a => a.GetType().Equals(typeof(LogAttribute)));
|
||||||
|
|
||||||
|
return (LogAttribute)attribute;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -74,7 +74,7 @@ namespace ZR.Admin.WebApi.Filters
|
|||||||
//Elapsed = _stopwatch.ElapsedMilliseconds,
|
//Elapsed = _stopwatch.ElapsedMilliseconds,
|
||||||
operTime = DateTime.Now
|
operTime = DateTime.Now
|
||||||
};
|
};
|
||||||
GetRequestValue(sysOperLog, context.HttpContext);
|
HttpContextExtension.GetRequestValue(context.HttpContext, sysOperLog);
|
||||||
|
|
||||||
if (logAttribute != null)
|
if (logAttribute != null)
|
||||||
{
|
{
|
||||||
@ -110,29 +110,5 @@ namespace ZR.Admin.WebApi.Filters
|
|||||||
return (LogAttribute)attribute;
|
return (LogAttribute)attribute;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 设置请求参数
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="operLog"></param>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
public static void GetRequestValue(SysOperLog operLog, HttpContext context)
|
|
||||||
{
|
|
||||||
string reqMethod = operLog.requestMethod;
|
|
||||||
string param;
|
|
||||||
|
|
||||||
if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod))
|
|
||||||
{
|
|
||||||
context.Request.Body.Seek(0, SeekOrigin.Begin);
|
|
||||||
using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
|
|
||||||
//需要使用异步方式才能获取
|
|
||||||
param = reader.ReadToEndAsync().Result;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
param = context.Request.QueryString.Value.ToString();
|
|
||||||
}
|
|
||||||
operLog.operParam = param;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -84,7 +84,7 @@ namespace ZR.Admin.WebApi.Middleware
|
|||||||
operLocation = ip_info.Province + " " + ip_info.City,
|
operLocation = ip_info.Province + " " + ip_info.City,
|
||||||
operTime = DateTime.Now
|
operTime = DateTime.Now
|
||||||
};
|
};
|
||||||
LogActionFilter.GetRequestValue(sysOperLog, context);
|
HttpContextExtension.GetRequestValue(context, sysOperLog);
|
||||||
LogEventInfo ei = new(logLevel, "GlobalExceptionMiddleware", error);
|
LogEventInfo ei = new(logLevel, "GlobalExceptionMiddleware", error);
|
||||||
|
|
||||||
ei.Exception = ex;
|
ei.Exception = ex;
|
||||||
|
|||||||
@ -77,7 +77,7 @@ namespace ZR.Admin.WebApi
|
|||||||
|
|
||||||
services.AddMvc(options =>
|
services.AddMvc(options =>
|
||||||
{
|
{
|
||||||
options.Filters.Add(typeof(GlobalActionMonitor));//全局注册异常
|
options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
|
||||||
})
|
})
|
||||||
.AddJsonOptions(options =>
|
.AddJsonOptions(options =>
|
||||||
{
|
{
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user