Log.php
2.1 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Lib;
/**
 * 日志文件
 * @author:dc
 * @time 2023/3/14 10:26
 * Class Log
 * @package Lib
 */
class Log {
    /**
     * @var array
     */
    public array $filename = [];
    /**
     * @var array
     */
    public array $message = [];
    /**
     * @var self
     */
    private static self $instance;
    /**
     * Log constructor.
     */
    public function __construct()
    {
        $this->setFilename();
    }
    /**
     * 追加日志内容
     * @param string $message
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public static function append(string $message, $filename = null){
        if($filename){
            self::getInstance()->setFilename($filename);
        }
        self::getInstance()->message[$filename ? md5($filename) : 'default'][] = $message;
    }
    /**
     * @return Log
     */
    public static function getInstance(): Log
    {
        if (empty(static::$instance)){
            static::$instance = new Log();
        }
        return self::$instance;
    }
    /**
     * 设置日志文件
     * @param $filename
     * @author:dc
     * @time 2023/3/14 11:11
     */
    private function setFilename($filename=null){
        if($filename){
            $this->filename[md5($filename)] = $filename;
        }else{
            $this->filename['default'] = $filename = LOG_PATH.'/'.app()->nowDate().'.error.log';
        }
        // 创建目录
        if(!is_dir(dirname($filename))){
            @mkdir(dirname($filename),0755,true);
        }
    }
    /**
     * 写入日志
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public function write(){
        foreach ($this->filename as $key=>$fn){
            if(!empty($this->message[$key])){
                array_unshift($this->message[$key],app()->nowDateTime());
                $this->message[$key][] = PHP_EOL;
                @file_put_contents(
                    $fn,
                    implode(PHP_EOL."\t",$this->message[$key]),
                    FILE_APPEND
                );
                $this->message[$key] = [];
            }
        }
    }
}