純程式碼分享個人Monolog API Log,記錄請求&響應中介軟體

zhangwuphp發表於2021-07-14

Log Request:

<?php

namespace App\Http\Middleware;

use App\Libraries\ApiLog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

    public function terminate(Request $request, Response $response)
    {
        ApiLog::debug('api-log', sprintf("Request from %s\n", $request->getClientIp()) . $this->request($request) . "\n\nResponse:\n" . $this->response($request, $response));
    }

    public function request(Request $request) {
        $data = sprintf(
            "%s %s %s\n",
            $request->method(),
            $request->url() . (!empty($request->getQueryString()) ? '?' . $request->getQueryString() : ''),
            $request->getProtocolVersion()
        );
        foreach ($this->getHeaderList($request->header()) as $name => $value) {
            $data .= $name . ': ' . $value . "\n";
        }
        return $data . "\r\n" . file_get_contents('php://input');
    }

    private function getHeaderList($headers) {
        $headerList = [];
        foreach ($headers as $name => $value) {
            $name = ucwords(strtolower($name));
            $headerList[$name] = $value[0];
        }
        return $headerList;
    }

    private function response(Request $request, Response $response) {
        return $response->__toString();
    }
}

Libraries ApiLog:

<?php
namespace App\Libraries;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;

class ApiLog
{
    private static $channels = [];

    public function __invoke(array $config)
    {
        return self::getSystemLogger();
    }

    public static function getHandlers($channel)
    {
        $handlers = [];
        $formatter = new LineFormatter(null,null,true,true);
        $fileHandler = new RotatingFileHandler(storage_path()."/logs/{$channel}.log",0,Logger::DEBUG,true,0666,false);
        $fileHandler->setFormatter($formatter);
        $handlers[] = $fileHandler;
        return $handlers;
    }

    public static function getChannel($channel){

        if(isset(self::$channels[$channel])){
            return self::$channels[$channel];
        }else{
            $log =  new Logger($channel,self::getHandlers($channel));
            self::$channels[$channel] = $log;
            return $log;
        }
    }

    public function getSystemLogger(){
        return self::getChannel('laravel');
    }

    public static function emergency($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::EMERGENCY, $channel, $content, $context);
    }

    public static function alert($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::ALERT, $channel, $content, $context);
    }

    public static function critical($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::CRITICAL, $channel, $content, $context);
    }

    public static function error($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::ERROR, $channel, $content, $context);
    }

    public static function warning($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::WARNING, $channel, $content, $context);
    }

    public static function notice($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::NOTICE, $channel, $content, $context);
    }

    public static function info($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::INFO, $channel, $content, $context);
    }

    public static function debug($channel = 'laravel', $content = null, $context = []) {
        self::log(Logger::DEBUG, $channel, $content, $context);
    }

    public static function log($level, $channel = 'laravel', $content = null, $context = []) {
        $log = self::getChannel($channel);
        $log->addRecord($level, $content, $context);
    }

}

Route:

Route::middleware(['auth:api','log'])->get('/user', function (Request $request) {
    return $request->user();
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章