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;
        }
    }
}
相关推荐
小诸葛的博客3 小时前
Flannel UDP 模式的优缺点
网络协议·udp·php
桃子酱紫君4 小时前
华为配置篇-RSTP/MSTP实验
开发语言·华为·php
JPCstorm5 小时前
客服系统重构详细计划
php
智慧地球(AI·Earth)6 小时前
OpenAI for Countries:全球AI基础设施的“技术基建革命”
开发语言·人工智能·php
zhou1856 小时前
MySQL保姆级安装教程(附资源包+5分钟极速配置+环境变量调试技巧)
java·python·mysql·php
行思理8 小时前
JIT+Opcache如何配置才能达到性能最优
c++·php·jit
皓月盈江16 小时前
Linux电脑本机使用小皮面板集成环境开发调试WEB项目
linux·php·web开发·phpstudy·小皮面板·集成环境·www.xp.cn
向哆哆1 天前
Netty在Java网络编程中的应用:实现高性能的异步通信
java·网络·php
Rverdoser1 天前
代理服务器运行速度慢是什么原因
开发语言·前端·php
森叶1 天前
从 JIT 即时编译一直讲到CGI|FastGGI|WSGI|ASGI四种协议的实现细节
python·php·web