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 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
ejinxian10 小时前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
zorro_z11 小时前
PHP语法基础篇(九):正则表达式
php
高压锅_122021 小时前
思科与华为网络设备命令对比指南:从基础操作到高级配置
服务器·华为·php
SuperherRo1 天前
WEB攻防-文件包含&LFI&RFI&伪协议编码算法&无文件利用&黑白盒
php·文件包含·伪协议·lfi·无文件·黑白盒·rfi
用户Taobaoapi20141 天前
Taobao agent USA丨美国淘宝代购1688代采集运系统搭建指南
数据挖掘·php
蓝色记忆1 天前
Classmap 如何兼容旧代码
php
蓝色记忆1 天前
Composer PSR-4 自动加载机制的完整流程
php
only-lucky2 天前
C语言socket编程-补充
服务器·c语言·php
蓝黑20202 天前
PHP从字符串到数值的类型转换
php