private async Task RequestDataLog(HttpContext context, string opTime)
        {
            var request = context.Request;
            var sr      = new StreamReader(request.Body);

            var requestData = request.Method == "GET" || request.Method == "DELETE" ? HttpUtility.UrlDecode(request.QueryString.ObjToString(), Encoding.UTF8) : (await sr.ReadToEndAsync()).ObjToString();

            if (requestData.IsNotEmptyOrNull() && requestData.Length > 30)
            {
                requestData = requestData.Substring(0, 30);
            }

            var requestInfo = JsonConvert.SerializeObject(new UserAccessModel()
            {
                User          = _user.Name,
                IP            = IPLogMildd.GetClientIP(context),
                API           = request.Path.ObjToString().TrimEnd('/').ToLower(),
                BeginTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                OPTime        = opTime,
                RequestMethod = request.Method,
                RequestData   = requestData,
                Agent         = request.Headers["User-Agent"].ObjToString()
            });

            if (!string.IsNullOrEmpty(requestInfo))
            {
                // 自定义log输出
                Parallel.For(0, 1, e =>
                {
                    LogLock.OutSql2Log("RecordAccessLogs", new string[] { requestInfo + "," }, false);
                });

                request.Body.Position = 0;
            }
        }
Esempio n. 2
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (Appsettings.app("Middleware", "RecordAccessLogs", "Enabled").ObjToBool())
            {
                var api        = context.Request.Path.ObjToString().TrimEnd('/').ToLower();
                var ignoreApis = Appsettings.app("Middleware", "RecordAccessLogs", "IgnoreApis");

                // 过滤,只有接口
                if (api.Contains("api") && !ignoreApis.Contains(api))
                {
                    _stopwatch.Restart();
                    var userAccessModel = new UserAccessModel();

                    HttpRequest request = context.Request;

                    userAccessModel.API           = api;
                    userAccessModel.User          = _user.Name;
                    userAccessModel.IP            = IPLogMildd.GetClientIP(context);
                    userAccessModel.BeginTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    userAccessModel.RequestMethod = request.Method;
                    userAccessModel.Agent         = request.Headers["User-Agent"].ObjToString();


                    // 获取请求body内容
                    if (request.Method.ToLower().Equals("post") || request.Method.ToLower().Equals("put"))
                    {
                        // 启用倒带功能,就可以让 Request.Body 可以再次读取
                        request.EnableBuffering();

                        Stream stream = request.Body;
                        byte[] buffer = new byte[request.ContentLength.Value];
                        stream.Read(buffer, 0, buffer.Length);
                        userAccessModel.RequestData = Encoding.UTF8.GetString(buffer);

                        request.Body.Position = 0;
                    }
                    else if (request.Method.ToLower().Equals("get") || request.Method.ToLower().Equals("delete"))
                    {
                        userAccessModel.RequestData = HttpUtility.UrlDecode(request.QueryString.ObjToString(), Encoding.UTF8);
                    }

                    // 获取Response.Body内容
                    var originalBodyStream = context.Response.Body;
                    using (var responseBody = new MemoryStream())
                    {
                        context.Response.Body = responseBody;

                        await _next(context);

                        var responseBodyData = await GetResponse(context.Response);

                        await responseBody.CopyToAsync(originalBodyStream);
                    }

                    // 响应完成记录时间和存入日志
                    context.Response.OnCompleted(() =>
                    {
                        _stopwatch.Stop();

                        userAccessModel.OPTime = _stopwatch.ElapsedMilliseconds + "ms";

                        // 自定义log输出
                        var requestInfo = JsonConvert.SerializeObject(userAccessModel);
                        //Parallel.For(0, 1, e =>
                        //{
                        //    LogLock.OutSql2Log("RecordAccessLogs", new string[] { requestInfo + "," }, false);
                        //});

                        var logFileName = FileHelper.GetAvailableFileNameWithPrefixOrderSize(_environment.ContentRootPath, "RecordAccessLogs");
                        SerilogServer.WriteLog(logFileName, new string[] { requestInfo + "," }, false);


                        return(Task.CompletedTask);
                    });
                }
                else
                {
                    await _next(context);
                }
            }
            else
            {
                await _next(context);
            }
        }