thinkphp日志记录到文件

日志

php 复制代码
//控制器中
//这种方法调用的话,在general_technology下按照日期写入日志
LogService::requestLog('general_technology',$this->baseUrl .$url,$params,$res);
LogService::responseLog('general_technology/hebei_product_add_error', $syncData,$msg);
LogService::responseLog('general_technology/hebei_product_add_error', $syncData,$exception->getMessage());


//lOGservice

<?php

namespace app\common\service;

class LogService
{
    /**
     * 三方对接请求记录
     * @param string $apiUserId
     * @param        $msg
     * @param array  $data
     * @return void
     */
    public static function apiUserLog(string $apiUserId, $msg, array $data = [])
    {
        if (!is_string($msg) && empty($data)) {
            $data = $msg;
            $msg = '';
        }

        file_put_contents(self::buildFilePath("apiUser/{$apiUserId}", true, true), date('YmdHis') . "\t" . request()->ip() . "\t" . request()->method() . "\t" . request()->url(true) . "\t" . $msg . "\t" . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND);
    }

    /**
     * 三方对接主动发起请求记录
     * @param string $apiUserId
     * @param string $url
     * @param        $params
     * @param        $response
     * @return void
     */
    public static function apiUserRequestLog(string $apiUserId, string $url, $params, $response)
    {
        $params = is_string($params) ? $params : json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $response = is_string($response) ? $response : json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        file_put_contents(self::buildFilePath("apiUser/{$apiUserId}", 'request.log', true), date('YmdHis') . "\t$url\t$params\t{$response}" . PHP_EOL, FILE_APPEND);
    }

    /**
     * 通用请求外部记录
     * @param string       $filePath
     * @param string       $url
     * @param string|array $params
     * @param string|array $response
     * @return void
     */
    public static function requestLog(string $filePath, string $url, $params, $response)
    {
        is_string($params) || $params = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        is_string($response) || $response = json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        file_put_contents(self::buildFilePath($filePath, 'request.log', true), date('YmdHis') . "\t$url\t$params\t{$response}" . PHP_EOL, FILE_APPEND);
    }

    /**
     * 通用外部请求记录
     * @param string       $filePath 日志文件路径
     * @param string|array $params   请求参数
     * @param string       $msg      其他消息
     * @return void
     */
    public static function responseLog(string $filePath, $params, string $msg = '')
    {
        is_string($params) || $params = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        file_put_contents(self::buildFilePath($filePath, true, true), date('YmdHis') . "\t" . request()->ip() . "\t" . request()->method() . "\t" . request()->url(true) . "\t$params\t$msg" . PHP_EOL, FILE_APPEND);
    }

    /**
     * 通用日志记录
     * @param string       $path     目录
     * @param string|bool  $fileName 文件名(true按日志切割)
     * @param string|mixed $msg      不为字符串时作为data处理
     * @param mixed        $data
     * @return void
     */
    public static function common(string $path, $fileName, $msg, $data = [])
    {
        $isDateSplit = is_bool($fileName);
        if ($isDateSplit) {
            $fileName = true;
        }

        if (!is_string($msg) && empty($data)) {
            $data = $msg;
            $msg = '';
        }

        $calledInfo = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0] ?? [];
        $calledInfo = ($calledInfo['file'] ?? '' ? str_replace(ROOT_PATH, '', $calledInfo['file']) : '') . ($calledInfo['type'] ?? '') . ($calledInfo['line'] ?? '');

        file_put_contents(self::buildFilePath($path, $fileName, $isDateSplit), date('YmdHis') . "\t{$calledInfo}\t{$msg}\t" . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND);
    }

    /**
     * 构建日志文件路径
     * @param string      $path        目录
     * @param string|bool $fileName    文件名(true自动生成,false返回目录路径)
     * @param bool        $isDateSplit 是否按日期切割目录
     * @return string
     */
    public static function buildFilePath(string $path, $fileName = false, bool $isDateSplit = false): string
    {
        $path = RUNTIME_PATH . 'logService' . DS . str_replace('/', DS, trim($path ?: 'default', '/'));

        $isDateSplit && $path .= DS . date('Ym');

        is_dir($path) || @mkdir($path, 0777, true);

        if ($fileName === false) {
            return $path;
        } elseif (is_string($fileName)) {
            $isDateSplit && $fileName = date('d') . ($fileName ? ('_' . $fileName) : '');

            return $path . DS . $fileName;
        } else {
            $fileName = ($isDateSplit ? date('d') : date('Ymd')) . '.log';

            return $path . DS . $fileName;
        }
    }
}
相关推荐
catchadmin7 小时前
PHP8.5 的新 URI 扩展
开发语言·后端·php
G佳伟9 小时前
yii2添加新的modules完为什么访问的时候报错404
php
亿坊电商19 小时前
在PHP框架里如何进行数据库连接?
数据库·oracle·php
Q_Q51100828520 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
WordPress学习笔记21 小时前
安装WordPress时没生成wp-config.php的解决方法
php·wp-config
浪裡遊1 天前
Nivo图表库全面指南:配置与用法详解
前端·javascript·react.js·node.js·php
notillusion1 天前
KWW#71843
java·php·程序优化
notillusion1 天前
TRX#22597
java·php·程序优化
、花无将1 天前
PHP:下载、安装、配置,与apache搭建
android·php·apache
Q_Q5110082851 天前
python+django/flask婚纱摄影拍照管理系统
spring boot·python·django·flask·node.js·php