public RequestResponseLoggingMiddleware(RequestDelegate next) { _next = next; _stopwatch = new Stopwatch(); _model = new DBLoggerModel(); }
/* * 日志内容: * 调用时间======调用方法及控制器========调用人=======消耗时间==========请求IP=====请求方式======请求参数 */ private async void LogWriter(ActionExecutedContext context) { //调用的方法 var methodName = context.RouteData.Values["Action"]?.ToString(); //context.ActionDescriptor.DisplayName, //调用的控制器 var controllerName = context.RouteData.Values["controller"]?.ToString(); if (methodName.ToLower() == "" || controllerName.ToLower() == "logger") { //查询日志不记录 return; } //这是获取自定义参数的方法(从token中获取用户名) var auth = context.HttpContext.AuthenticateAsync().Result?.Principal?.Claims; var account = string.Empty; if (auth != null) {//获取当前登录的帐号 account = auth?.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value; } var obj = new DBLoggerModel { CallTime = DateTime.Now, //获取调用账号(如果是匿名则表示没有登录) AccountName = account, //请求IP RequestIP = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), // context.HttpContext.Request.Host.Host, //调用的方法 MethodName = methodName, //context.ActionDescriptor.DisplayName, //调用的控制器 ControllerName = controllerName, //消耗时间 SpendTime = stopwatch.ElapsedMilliseconds, //请求方式POST,GET RequestType = context.HttpContext.Request.Method, //请求参数 RequestParameters = string.Join(",", requestPara) }; //只处理以下几种情况 if ((context.Result as JsonResult) != null) { obj.ResponseParameters = QWPlatform.SystemLibrary.Utils.Strings.ObjectToJson((context.Result as JsonResult)?.Value, true, true); } else if ((context.Result as ContentResult) != null) { obj.ResponseParameters = QWPlatform.SystemLibrary.Utils.Strings.ObjectToJson((context.Result as ContentResult)?.Content, true, true); } else if ((context.Result as ObjectResult) != null) { obj.ResponseParameters = QWPlatform.SystemLibrary.Utils.Strings.ObjectToJson((context.Result as ObjectResult)?.Value, true, true); } obj.ResponseParameters = obj.ResponseParameters? .Replace("\\r\\n", "") .Replace("\\", "") .Replace(" ", ""); //写入日志库中 var logger = await OrleansClient.Instance.CreateInstance <IDBLogger>(); logger.Add(obj); //输出日志 Logger.Instance.Debug(obj.ToJson()); }