Log.php
2.3 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
114
115
116
117
118
119
120
121
122
123
124
125
<?php
namespace Lib;
/**
 * 日志文件
 * @author:dc
 * @time 2023/3/14 10:26
 * Class Log
 * @package Lib
 */
class Log {
    /**
     * @var array
     */
    protected array $filename = [];
    /**
     * @var array
     */
    protected array $message = [];
    /**
     * @var self
     */
    private static self $instance;
    /**
     * Log constructor.
     */
    public function __construct()
    {
    }
    /**
     * 追加日志内容
     * @param string $message
     * @param null $filename
     * @return Log
     * @author:dc
     * @time 2024/7/18 14:12
     */
    public static function append(string $message, $filename = null){
        if($filename){
            self::getInstance()->setFilename($filename);
        }
        self::getInstance()->message[$filename ? md5($filename) : 'default'][] = date('Y-m-d H:i:s  ').$message;
        return self::getInstance();
    }
    /**
     * @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){
        $this->filename[md5($filename)] = $filename;
        // 创建目录
        if(!is_dir(dirname($filename))){
            @mkdir(dirname($filename),0755,true);
        }
    }
    /**
     * @return array
     */
    protected function getFilename($key=null): string
    {
        return $this->filename[$key]??LOG_PATH.'/'.date('Y-m-d').'.error.log';
    }
    /**
     * 写入日志
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public function write(){
        foreach ($this->message as $key=>$msg){
            $fo = @fopen($this->getFilename($key),'a');
            if(!$fo){
                $fo = @fopen($this->getFilename(),'a');
            }
            if($fo){
                foreach ($msg as $log){
                    @fwrite($fo,$log.PHP_EOL);
                }
                @fclose($fo);
            }
            $this->message[$key] = null;
            unset($this->message[$key]);
        }
    }
    public function __destruct()
    {
        $this->write();
    }
}