• [Laravel系列] 框架中增加记录access log的日志中间件


    有时候我们需要记录下请求和响应的全部参数

    这样可以方便排查问题

    现在通过中间件的形式增加一个AccessLog的记录功能

    appHttpMiddleware目录下增加AccessLog.php 文件

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    
    class AccessLog
    {
        /**
         * 路由全局中间件
         *
         * @param  IlluminateHttpRequest  $request
         * @param  Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $requestTime = microtime(true);
    
            $response = $next($request);
    
            $rq_time = microtime(true) - $requestTime;
    
            $log = [
                'method' => $request->method(),
                'url' => $request->fullUrl(),
                'param' => json_encode($request->all(), JSON_UNESCAPED_UNICODE),
                'response' => $response->getContent(),
                'req_header' => json_encode($request->header(), JSON_UNESCAPED_UNICODE),
                'resp_header' => json_encode($response->headers->all(), JSON_UNESCAPED_UNICODE),
                'ip_address' => $request->ip(),
                'rq_time' => sprintf("%.2f", $rq_time),
            ];
    
            logger()->channel('access')->info($log);
    
            return $response;
        }
    }

    app/Http/Kernel.php 注册一下AppHttpMiddlewareAccessLog::class

    class Kernel extends HttpKernel
    {
        /**
         * The application's global HTTP middleware stack.
         *
         * These middleware are run during every request to your application.
         *
         * @var array
         */
        protected $middleware = [
            // AppHttpMiddlewareTrustHosts::class,
            AppHttpMiddlewareTrustProxies::class,
            FruitcakeCorsHandleCors::class,
            AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
            IlluminateFoundationHttpMiddlewareValidatePostSize::class,
            AppHttpMiddlewareTrimStrings::class,
            IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
            AppHttpMiddlewareAccessLog::class
        ];

    增加一下配置

    config/logging.php

            'access' => [
                'driver' => 'daily',
                'path' => env('LOG_PATH_ACCESS', storage_path('logs/access/laravel.log')),
                'level' => env('LOG_LEVEL', 'debug'),
                'days' => 14,
            ],

    请求一下就会看到生成文件 

    开源作品

    GO-FLY,一套可私有化部署的免费开源客服系统,安装过程不超过五分钟(超过你打我 !),基于Golang开发,二进制文件可直接使用无需搭开发环境,下载zip解压即可,仅依赖MySQL数据库,是一个开箱即用的网页在线客服系统,致力于帮助广大开发者/中小站长快速整合私有客服功能
    github地址:go-fly
    官网地址:https://gofly.sopans.com
  • 相关阅读:
    第6章 解决问题 6-1 机器学习解决问题(1)
    第5章 常见的算法和分类 5-2 机器学习常见算法和分类(2)
    Linux中Shell数组的笔记
    Linux中Shell数组的笔记
    Linux中Shell中取消变量和特殊变量的笔记
    Linux中Shell中取消变量和特殊变量的笔记
    Linux实现MYSQl数据库的定时备份
    Linux中su和sudo的用法整理
    Linux用户组笔记整理
    Linux 用户管理命令笔记
  • 原文地址:https://www.cnblogs.com/taoshihan/p/15467119.html
Copyright © 2020-2023  润新知