作者 karlet

feat:增加logger类

logs
... ...
<?php
namespace Jiaoyin;
require_once __DIR__ . '/functions.php';
class Logger
{
private string $logPath;
private bool $dateSlice;
private array $types;
public function __construct($logPath, $types = ['info','warning','error'], $dateSlice = false)
{
$this->logPath = $logPath;
$this->dateSlice = $dateSlice;
$this->types = $types;
}
public function debug($msg){
$this->log($msg,'debug');
}
public function info($msg){
$this->log($msg,'info');
}
public function warning($msg){
$this->log($msg,'warning');
}
public function error($msg){
$this->log($msg,'error');
}
private function log($msg, $type){
$msg = '['.timeFormat('ms').']['.$type.']:'.$msg.PHP_EOL;
echo $msg;
if (!in_array($type,$this->types)){
return;
}
if ($this->dateSlice) {
$path = $this->logPath.'/'.date('Y-m-d');
}else{
$path = $this->logPath;
}
$file = $path.'/'.$type.'.log';
$this->save($file,$msg,$type);
}
private function save($file,$msg, $type='info'){
\Swoole\Coroutine::create(function () use ($file,$msg,$type) {
$this->checkFileDir($file);
file_put_contents($file,$msg,FILE_APPEND);
});
}
private function checkFileDir($file){
// 获取目录路径
$directoryPath = dirname($file);
if (!is_dir($directoryPath)) {
// 如果目录不存在,则创建目录
mkdir($directoryPath, 0755, true);
}
}
}
\ No newline at end of file
... ...
<?php
require_once __DIR__ . '/../src/Logger.php';
use Jiaoyin\Logger;
$log = new Logger('./logs');
$log->info('hello world');
$log->error('hello world error');
$log2 = new Logger('./logs',['info','error']);
$log2->warning('hello world');
$log2->error( 'hello world error');
$log3 = new Logger('./logs',['info','error'],true);
$log3->info('hello world dataSlice test');
\ No newline at end of file
... ...