作者 karlet

feat:增加logger类

  1 +<?php
  2 +
  3 +namespace Jiaoyin;
  4 +require_once __DIR__ . '/functions.php';
  5 +class Logger
  6 +{
  7 + private string $logPath;
  8 + private bool $dateSlice;
  9 + private array $types;
  10 +
  11 + public function __construct($logPath, $types = ['info','warning','error'], $dateSlice = false)
  12 + {
  13 + $this->logPath = $logPath;
  14 + $this->dateSlice = $dateSlice;
  15 + $this->types = $types;
  16 + }
  17 + public function debug($msg){
  18 + $this->log($msg,'debug');
  19 + }
  20 + public function info($msg){
  21 + $this->log($msg,'info');
  22 + }
  23 + public function warning($msg){
  24 + $this->log($msg,'warning');
  25 + }
  26 + public function error($msg){
  27 + $this->log($msg,'error');
  28 + }
  29 + private function log($msg, $type){
  30 + $msg = '['.timeFormat('ms').']['.$type.']:'.$msg.PHP_EOL;
  31 + echo $msg;
  32 + if (!in_array($type,$this->types)){
  33 + return;
  34 + }
  35 + if ($this->dateSlice) {
  36 + $path = $this->logPath.'/'.date('Y-m-d');
  37 + }else{
  38 + $path = $this->logPath;
  39 + }
  40 + $file = $path.'/'.$type.'.log';
  41 + $this->save($file,$msg,$type);
  42 + }
  43 + private function save($file,$msg, $type='info'){
  44 + \Swoole\Coroutine::create(function () use ($file,$msg,$type) {
  45 + $this->checkFileDir($file);
  46 + file_put_contents($file,$msg,FILE_APPEND);
  47 + });
  48 + }
  49 + private function checkFileDir($file){
  50 + // 获取目录路径
  51 + $directoryPath = dirname($file);
  52 + if (!is_dir($directoryPath)) {
  53 + // 如果目录不存在,则创建目录
  54 + mkdir($directoryPath, 0755, true);
  55 + }
  56 + }
  57 +}
  1 +<?php
  2 +
  3 +require_once __DIR__ . '/../src/Logger.php';
  4 +
  5 +use Jiaoyin\Logger;
  6 +
  7 +$log = new Logger('./logs');
  8 +$log->info('hello world');
  9 +$log->error('hello world error');
  10 +
  11 +$log2 = new Logger('./logs',['info','error']);
  12 +$log2->warning('hello world');
  13 +$log2->error( 'hello world error');
  14 +
  15 +$log3 = new Logger('./logs',['info','error'],true);
  16 +$log3->info('hello world dataSlice test');