PHP 基于Monolog 写入日志

2021-09-29  本文已影响0人  没心没肺最开心

网上一知半解的真的折磨人。这次给全的。composer安装Monolog就自行百度吧,日志文件先上代码:

基于版本: "monolog/monolog": "1.25.0"

<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\JsonFormatter;
use Monolog\Processor\WebProcessor;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\UidProcessor;
use Monolog\Processor\MemoryPeakUsageProcessor;


/**
 * 日志类
 *  单列模式实现的逻辑根据自己的业务调整,这边按类做了单列
 */
class XxxLogger{

    private static $ins_map;
    private $logger;
    private $env;
    public static function get_ins($channel_mame){
        if (empty(self::$ins_map[$channel_mame])){
            self::$ins_map[$channel_mame] = new AisouLogger();
            $logger = new Logger($channel_mame);
            //博主内部逻辑
            $path = \XYZ::get_instance()->config('path');
            $env = \XYZ::get_instance()->config('env');
            // 将日志内容json化
            $formatter = new JsonFormatter();
           // 博主内部逻辑,生产环境是INFO级别日志,别的环境是DEBUG
            if ($env == 'product'){
                $level = Logger::INFO;
            }else{
                $level = Logger::DEBUG;
            }
            // 博主内部逻辑,主要区分web数据和脚本数据
            if (substr(php_sapi_name(), 0, 3) == 'cli') {
                $stream = new StreamHandler($path."/{$channel_mame}-cli-".date('Ymd').'.log', $level);
            }else{
                $stream = new StreamHandler($path."/{$channel_mame}-fpm-".date('Ymd').'.log', $level);
            }

            // 增加JSON格式
            $stream ->setFormatter($formatter);
            // 增加操作方式
            $logger->pushHandler($stream);
            // 增加处理器
            $logger-> pushProcessor(new WebProcessor);
            $logger-> pushProcessor(new IntrospectionProcessor);
            $logger-> pushProcessor(new MemoryPeakUsageProcessor);
            $logger-> pushProcessor(new UidProcessor);
            self::$ins_map[$channel_mame]->logger =$logger;
        }
        return self::$ins_map[$channel_mame];
    }

    public static function get_logger($channel_mame = 'aisou_log'){
        return self::get_ins($channel_mame) ->logger;
    }
}

使用方法:

// 某个条件下,增加web访问日志   
 if($condition){
            $content = [
                'headers' => $_SERVER,
                'post' => $_POST,
                'get' => $_GET,
                'input' => file_get_contents('php://input'),
                'response' =>  $result
            ];
            \XxxLogger::get_logger('api_logger')->info('接口访问日志',$content);
        }

这样日志文件就会生效

上一篇下一篇

猜你喜欢

热点阅读