06创建laravel5.8前后台api项目--记录请求和响应日志

修改config/app.php代码,将UTC修改为Asia/Shanghai,确保写入日志的时区为东8区

/*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    // 'timezone' => 'UTC',
    'timezone' => 'Asia/Shanghai',

创建文件app/Http/Middleware/RequestLog.php

<?php

namespace App\Http\Middleware;

use Closure;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class RequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $arr      = parse_url($request->fullUrl());
        $path     = array_get($arr, 'path', '');
        $log_file = 'logs/'.trim($path, '/').'/'.date("Y-m-d").'.log';
        
        // create a log channel
        $log = new Logger('tracking');
        $log->pushHandler(new StreamHandler(storage_path($log_file), Logger::INFO));

        // add records to the log
        $log->info(json_encode([
            'path'     => $path,
            'method'   => $request->method(),
            'header'   => $request->header(),
            'request'  => $request->all(),
            'response' => $response->original,
        ], JSON_UNESCAPED_UNICODE));

        return $response;
    }
}

修改app/Http/Kernel.php代码,给api增加中间件 \App\Http\Middleware\RequestLog::class

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            \App\Http\Middleware\RequestLog::class, //新增加这一行代码
        ],
    ];

用postman测试一下日志

查看结果:

 

源代码地址:https://github.com/windawake/laravel-repository-pratice/tree/master

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值