php简单实现 记录接口请求日志

先看使用效果

 

执行代码:

public function mainLogic()
{
   logs();    // 在接口开始时调用,可以放到父类的构造方法里面
   // 接口逻辑....
}

请求参数:

日志:

 

封装的代码:

 

/**
     * 写入日志
     * @param array | string $content 日志内容
     * @param string $filename        文件名
     * @param string $type            自定义标签
     * @param bool $isDistinguishDay  是否区分天存放
     * @return bool|int
     */
    public static function log($content, $filename, $type = 'info', $isDistinguishDay = true)
    {
        $path = dirname(__DIR__). '/runtime/myLog/';  // 自定义路径

        if (!file_exists($path)) {
             @mkdir($path, 0755);    // 权限设置
        }

        if ($isDistinguishDay) {
            $logFile = $path . $filename . "-" . date("Ymd") . ".log";
        } else {
            $logFile = $path . $filename  . ".log";
        }

        if (is_array($content) || is_object($content)) {   // 便于一些数组传参
            $content = json_encode($content);
        }

        $date = date("Y-m-d H:i:s");
        return file_put_contents($logFile, $date . " [$type] " . $content . PHP_EOL, FILE_APPEND);
    }



// 日志记录
function logs()
{
    $type = strtolower(\request()->method());   // 识别请求方式

    $logMsg = "请求者的ip是 ".\request()->server()['REMOTE_ADDR']." ,    
               当前请求类型是:".$type.' ,接口是:'.\request()->url().' ,
               请求参数是'.json_encode(input("$type."),JSON_UNESCAPED_UNICODE);

    \Common::log($logMsg, 'commonLog');     // 调用上面的方法
}

 

posted @ 2022-08-29 09:50  jaychou、  阅读(619)  评论(0编辑  收藏  举报