Logger.php 1.7 KB
<?php

namespace jytools;

require_once __DIR__ . '/func.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);
        }
    }
}