Logger.php
1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?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);
}
}
}