網(wǎng)上一知半解的真的折磨人混驰。這次給全的。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;
/**
* 日志類
* 單列模式實(shí)現(xiàn)的邏輯根據(jù)自己的業(yè)務(wù)調(diào)整螃壤,這邊按類做了單列
*/
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);
//博主內(nèi)部邏輯
$path = \XYZ::get_instance()->config('path');
$env = \XYZ::get_instance()->config('env');
// 將日志內(nèi)容json化
$formatter = new JsonFormatter();
// 博主內(nèi)部邏輯,生產(chǎn)環(huán)境是INFO級(jí)別日志倡怎,別的環(huán)境是DEBUG
if ($env == 'product'){
$level = Logger::INFO;
}else{
$level = Logger::DEBUG;
}
// 博主內(nèi)部邏輯迅耘,主要區(qū)分web數(shù)據(jù)和腳本數(shù)據(jù)
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;
}
}
使用方法:
// 某個(gè)條件下,增加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);
}
這樣日志文件就會(huì)生效