-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.php
More file actions
169 lines (143 loc) · 5.06 KB
/
logger.php
File metadata and controls
169 lines (143 loc) · 5.06 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<?php
/**
* 日志记录类(增强版)
* 支持JSON格式、请求ID追踪、上下文信息
*/
class Logger {
private string $logDir;
private string $logFile;
private string $jsonLogFile;
private static ?string $requestId = null;
private bool $jsonFormat = false;
public function __construct(bool $jsonFormat = false) {
$this->logDir = $this->resolveLogDir();
$this->logFile = $this->logDir . 'netwatch_' . date('Y-m-d') . '.log';
$this->jsonLogFile = $this->logDir . 'netwatch_' . date('Y-m-d') . '.json.log';
$this->jsonFormat = $jsonFormat;
// 生成请求ID
if (self::$requestId === null) {
self::$requestId = $this->generateRequestId();
}
}
private function resolveLogDir(): string {
$dir = defined('LOG_PATH') ? (string)LOG_PATH : '';
if ($dir !== '') {
$dir = rtrim($dir, "\\/ ") . DIRECTORY_SEPARATOR;
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
if (is_dir($dir) && is_writable($dir)) {
return $dir;
}
}
$fallback = rtrim(sys_get_temp_dir(), "\\/ ") . DIRECTORY_SEPARATOR . 'netwatch_logs' . DIRECTORY_SEPARATOR;
if (!is_dir($fallback)) {
@mkdir($fallback, 0755, true);
}
if (is_dir($fallback) && is_writable($fallback)) {
return $fallback;
}
return '';
}
private function safeAppend(string $filePath, string $content): bool {
if ($filePath === '') {
return false;
}
$result = @file_put_contents($filePath, $content, FILE_APPEND | LOCK_EX);
return $result !== false;
}
/**
* 生成唯一请求ID
*/
private function generateRequestId(): string {
return substr(md5(uniqid((string)mt_rand(), true)), 0, 8);
}
/**
* 获取当前请求ID
*/
public static function getRequestId(): string {
if (self::$requestId === null) {
self::$requestId = substr(md5(uniqid((string)mt_rand(), true)), 0, 8);
}
return self::$requestId;
}
/**
* 写入日志(文本格式)
*/
private function writeLog(string $level, string $message, array $context = []): void {
$timestamp = date('Y-m-d H:i:s');
$requestId = self::getRequestId();
// 文本格式日志
$contextStr = !empty($context) ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
$logEntry = "[$timestamp] [$requestId] [$level] $message$contextStr" . PHP_EOL;
if (!$this->safeAppend($this->logFile, $logEntry)) {
error_log(rtrim($logEntry));
}
// JSON格式日志(可选)
if ($this->jsonFormat) {
$this->writeJsonLog($level, $message, $context);
}
}
/**
* 写入JSON格式日志
*/
private function writeJsonLog(string $level, string $message, array $context = []): void {
$logData = [
'timestamp' => date('c'),
'level' => $level,
'request_id' => self::getRequestId(),
'message' => $message,
'context' => $context,
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'cli',
'uri' => $_SERVER['REQUEST_URI'] ?? 'cli',
'method' => $_SERVER['REQUEST_METHOD'] ?? 'cli'
];
$jsonEntry = json_encode($logData, JSON_UNESCAPED_UNICODE) . PHP_EOL;
if (!$this->safeAppend($this->jsonLogFile, $jsonEntry)) {
error_log(rtrim($jsonEntry));
}
}
/**
* 启用/禁用JSON格式日志
*/
public function setJsonFormat(bool $enabled): void {
$this->jsonFormat = $enabled;
}
public function debug($message, array $context = []): void {
if (LOG_LEVEL === 'DEBUG') {
$this->writeLog('DEBUG', $message, $context);
}
}
public function info($message, array $context = []): void {
if (in_array(LOG_LEVEL, ['DEBUG', 'INFO'])) {
$this->writeLog('INFO', $message, $context);
}
}
public function warning($message, array $context = []): void {
if (in_array(LOG_LEVEL, ['DEBUG', 'INFO', 'WARNING'])) {
$this->writeLog('WARNING', $message, $context);
}
}
public function error($message, array $context = []): void {
$this->writeLog('ERROR', $message, $context);
}
public function getRecentLogs($lines = 100) {
if (!file_exists($this->logFile)) {
return [];
}
$file = new SplFileObject($this->logFile);
$file->seek(PHP_INT_MAX);
$totalLines = $file->key();
$startLine = max(0, $totalLines - $lines);
$logs = [];
$file->seek($startLine);
while (!$file->eof()) {
$line = trim($file->current());
if (!empty($line)) {
$logs[] = $line;
}
$file->next();
}
return $logs;
}
}