using DopInterfacePlatform.Entity;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace DopInterfacePlatform
{
///
/// 记录日志
///
public class LogFilter : ActionFilterAttribute
{
// private IBusApiOperatorRepository api_operator_repository;
private Stopwatch stopwach { get; set; }
private string actionArguments { get; set; }
private Dictionary keyValuePairs { set; get; }
private readonly DopInterfacePlatformContext _context;
public LogFilter(DopInterfacePlatformContext context)
{
_context = context;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
//is not controller return
if (!(context.ActionDescriptor is ControllerActionDescriptor action))
return;
var request = context.HttpContext.Request;
//启动倒带方式
request.EnableBuffering();
if (request.Method.ToLower().Equals("post"))
{
request.Body.Position = 0;
using var requestReader = new StreamReader(request.Body);
var requestContent = requestReader.ReadToEnd();
request.Body.Position = 0;
}
stopwach = new Stopwatch();
stopwach.Start();
if(context.ActionArguments.Count>0)
{
actionArguments = context.ActionArguments.ToJsonString();
}
stopwach = new Stopwatch();
stopwach.Start();
}
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
//is not controller return
if (!(context.ActionDescriptor is ControllerActionDescriptor action))
return;
stopwach.Stop();
var time = stopwach.Elapsed;
// string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
string logMethod = context.HttpContext.Request.Method;
dynamic result = context.Result.GetType().Name == "EmptyResult"
? new { Value = "无返回结果" }
: context.Result as dynamic;
string res = "在返回结果前发生了异常";
try
{
if (result != null)
{
res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
}
}
catch (System.Exception ex)
{
res = "日志未获取到结果,返回的数据无法序列化!" + ex.Message;
}
//转换ActionDescriptor
string logController = context.RouteData.Values["Controller"].ToString();
var logAction = context.RouteData.Values["Action"].ToString();
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
var ipAddress = context.HttpContext.Connection.RemoteIpAddress.ToString();
if(logAction!="GetToken")
{
var model = new InterfacePlatformLog();
if (actionArguments == null)
{
actionArguments = "";
}
model.operatorcol_time = DateTime.Now;
model.operatorcol_ip = ipAddress;
model.operatorcol_duration = (int)time.TotalSeconds * 1000;
model.operatorcol_request = $"{logController}-{logAction}-{logMethod}-{actionArguments}"; //调用入参
model.operatorcol_respone = res; //调用出参
_context.InterfacePlatformLog.Add(model);
_context.SaveChanges();
}
}
}
}