public async Task Invoke(HttpContext context) { _stopwatch.Restart(); HttpRequest request = context.Request; //获取登录人员账户 _model.AccountName = context.User.Identity.Name; //获取IP地址 _model.RequestIP = context.Connection.RemoteIpAddress.MapToIPv4().ToString(); //请求方法 _model.RequestType = request.Method; //方法名称(这里是调用路径) _model.MethodName = request.Path.ToString(); //调用时间 _model.CallTime = DateTime.Now; // 获取请求body内容 if (request.Method.ToLower().Equals("post")) { // 启用倒带功能,就可以让 Request.Body 可以再次读取 request.EnableBuffering(); Stream stream = request.Body; byte[] buffer = new byte[request.ContentLength.Value]; stream.Read(buffer, 0, buffer.Length); //获取请求参数 _model.RequestParameters = Encoding.UTF8.GetString(buffer); //重置数据流位置 request.Body.Position = 0; } else if (request.Method.ToLower().Equals("get")) { _model.RequestParameters = request.QueryString.Value; } // 获取Response.Body内容 var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { try { context.Response.Body = responseBody; await _next(context); //获取输出内容 _model.ResponseParameters = await GetResponse(context.Response); await responseBody.CopyToAsync(originalBodyStream); } catch (Exception ex) { Logger.Instance.Error("响应流发生异常", ex); return; } } // 响应完成记录时间和存入日志 context.Response.OnCompleted(() => { _stopwatch.Stop(); //计算消耗时间 _model.SpendTime = _stopwatch.ElapsedMilliseconds; var path = context.Request.Path.ToString(); if (path == "/" || path.Contains(".") || path.ToLower().Contains("swagger") || path.ToLower().Contains("/home/login") ) { return(Task.CompletedTask); } else { //写入日志库中 OrleansClient.Instance.CreateInstance <IDBLogger>().Result.Add(_model); //输出日志 Logger.Instance.Debug(_model.ToJson()); } return(Task.CompletedTask); }); }
/* * 日志内容: * 调用时间======调用方法及控制器========调用人=======消耗时间==========请求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()); }