-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogger.php
More file actions
407 lines (358 loc) · 10.7 KB
/
Logger.php
File metadata and controls
407 lines (358 loc) · 10.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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php
namespace WebStream\Log;
use WebStream\IO\File;
use WebStream\IO\Reader\FileReader;
use WebStream\IO\Writer\SimpleFileWriter;
use WebStream\Container\Container;
use WebStream\Exception\Extend\IOException;
use WebStream\Exception\Extend\LoggerException;
use WebStream\Log\Outputter\ILazyWriter;
use WebStream\Log\Outputter\IOutputter;
/**
* Loggerクラス
* @author Ryuichi Tanaka
* @since 2012/01/16
* @version 0.7
*/
class Logger
{
use LoggerUtils;
/**
* @var Logger ロガー
*/
private static Logger $logger;
/**
* @var LoggerFormatter ロガーフォーマッタ
*/
private static LoggerFormatter $formatter;
/**
* @var Container ログ設定コンテナ
*/
private static Container $config;
/**
* @var Container ログ設定コンテナ
*/
private Container $logConfig;
/**
* @var array<IOutputter> Outputterリスト
*/
private array $outputters;
/**
* @var Container IOコンテナ
*/
private Container $ioContainer;
/**
* @var File ログファイル
*/
private File $logFile;
/**
* @var File ステータスファイル
*/
private File $statusFile;
/**
* コンストラクタ
* @param Container ログ設定コンテナ
*/
private function __construct(Container $logConfig)
{
$this->logConfig = $logConfig;
$this->outputters = [];
$logFile = new File($logConfig->logPath);
$statusFile = new File($logConfig->statusPath);
$this->ioContainer = new Container();
$this->ioContainer->statusReader = function () use ($statusFile) {
return new FileReader($statusFile);
};
$this->ioContainer->statusWriter = function () use ($statusFile) {
return new SimpleFileWriter($statusFile->getFilePath());
};
$this->ioContainer->logWriter = function () use ($logFile) {
return new SimpleFileWriter($logFile->getFilePath());
};
$this->logFile = $logFile;
$this->statusFile = $statusFile;
}
/**
* デストラクタ
*/
public function __destruct()
{
$this->directWrite();
}
/**
* ログ設定を返却する
* @return Container ログ設定
*/
public function getConfig()
{
return $this->logConfig;
}
/**
* 遅延書き出しを有効にする
*/
public static function enableLazyWrite()
{
self::$logger->lazyWrite();
}
/**
* 即時書き出しを有効にする
*/
public static function enableDirectWrite()
{
self::$logger->directWrite();
}
/**
* インスタンスを返却する
* @return Logger ロガーインスタンス
*/
public static function getInstance()
{
return self::$logger;
}
/**
* ファイナライザ
*/
public static function finalize()
{
self::$config = null;
self::$logger = null;
self::$formatter = null;
}
/**
* Loggerを初期化する
* @param Container $config
*/
public static function init(Container $config)
{
self::$config = $config;
self::$logger = new Logger($config);
self::$formatter = new LoggerFormatter($config);
}
/**
* Loggerが初期化済みかどうかチェックする
* @return bool 初期化済みならtrue
*/
public static function isInitialized()
{
return self::$logger !== null;
}
/**
* Loggerメソッドの呼び出しを受ける
* @param string メソッド名(ログレベル文字列)
* @param array 引数
*/
public static function __callStatic($level, $arguments)
{
if (self::$logger === null || self::$formatter === null) {
if (self::$config !== null) {
self::init(self::$config);
} else {
throw new LoggerException("Logger is not initialized.");
}
}
call_user_func_array([self::$logger, "write"], array_merge([$level], $arguments));
}
/**
* Outputterを設定する
* @param array<IOutputter> $outputters Outputterリスト
*/
public function setOutputter(array $outputters)
{
foreach ($outputters as $outputter) {
if (!$outputter instanceof IOutputter) {
throw new LoggerException("Log outputter must implement WebStream\Log\Outputter\IOutputter.");
}
}
$this->outputters = $outputters;
}
/**
* タイムスタンプを取得する
* @return string タイムスタンプ
*/
private function getTimeStamp()
{
date_default_timezone_set('Asia/Tokyo');
$msec = sprintf("%2d", floatval(microtime()) * 100);
return strftime("%Y-%m-%d %H:%M:%S") . "," . $msec;
}
/**
* ログを書き出す
* @param string ログレベル文字列
* @param string 出力文字列
* @param array<mixed> 埋め込み値リスト
*/
public function write($level, $msg, $context = null)
{
if ($this->logConfig->logLevel > $this->toLogLevelValue($level)) {
return;
}
if (is_array($context) && count($context) > 0) {
// sprintfと同様の展開
// [a-zA-Z0-9_-\.] 以外もキーには指定可能だが仕様としてこれ以外は不可とする
preg_match_all('/\{\s*([a-zA-Z0-9._-]+)\s*?\}/', $msg, $matches);
foreach ($matches[1] as $index => $value) {
if (array_key_exists($value, $context)) {
$matches[1][$index] = $context[$value];
} else {
unset($matches[0][$index]);
}
}
$msg = str_replace($matches[0], $matches[1], $msg);
}
// ログローテート処理
$this->rotate();
try {
if (count($this->outputters) > 0) {
foreach ($this->outputters as $outputter) {
$outputter->write(self::$formatter->getFormattedMessage($msg, $level));
}
} else {
$this->ioContainer->logWriter->write(self::$formatter->getFormattedMessage($msg, $level) . PHP_EOL);
}
} catch (IOException $e) {
throw new LoggerException($e);
}
}
/**
* ログファイルをアーカイブする
* stream.log -> stream.(作成日時)-(現在日時).log
* @param string ログファイルパス
*/
private function rotate()
{
// ログファイルがない場合はローテートしない
if (!$this->logFile->exists()) {
return;
}
// ログローテート実行
if ($this->logConfig->rotateCycle !== null) {
$this->rotateByCycle();
} elseif ($this->logConfig->rotateSize !== null) {
$this->rotateBySize();
}
}
/**
* ログステータスファイルに書きこむ
* @throws IOException
*/
private function writeStatus()
{
$this->ioContainer->statusWriter->write(intval(preg_replace('/^.*\s/', '', microtime())));
}
/**
* ログステータスファイルを読み込む
* @return int UnixTime
* @throws LoggerException
*/
private function readStatus()
{
$content = $this->ioContainer->statusReader->read();
if (!preg_match('/^\d{10}$/', $content)) {
throw new LoggerException("Invalid log state file contents: " . $content);
}
return intval($content);
}
/**
* ステータスファイルを作成する
*/
private function createStatusFile()
{
// ステータスファイルがない場合は書きだす
if (!$this->statusFile->exists()) {
$this->writeStatus();
}
}
/**
* ローテートを実行する
* @param int 作成日時のUnixTime
* @param int 現在日時のUnixTime
*/
private function runRotate($from, $to)
{
$fromDate = date("YmdHis", $from);
$toDate = date("YmdHis", $to);
$archivePath = null;
if (preg_match('/(.*)\.(.+)/', $this->logConfig->logPath, $matches)) {
$archivePath = "$matches[1].${fromDate}-${toDate}.$matches[2]";
// mvを実行
$this->logFile->renameTo($archivePath);
// ステータスファイルを削除
$this->statusFile->delete();
}
}
/**
* 時間単位でローテートする
* stream.log -> stream.(作成日時)-(現在日時).log
*/
private function rotateByCycle()
{
$this->createStatusFile();
$now = intval(preg_replace('/^.*\s/', '', microtime()));
$createdAt = $this->readStatus();
$hour = intval(floor(($now - $createdAt) / 3600));
if ($hour >= $this->logConfig->rotateCycle) {
$this->runRotate($createdAt, $now);
}
}
/**
* サイズ単位でローテートする
* stream.log -> stream.(作成日時)-(現在日時).log
*/
private function rotateBySize()
{
$this->createStatusFile();
$now = intval(preg_replace('/^.*\s/', '', microtime()));
$createdAt = $this->readStatus();
$sizeKb = (int) floor($this->logFile->length() / 1024);
// 指定したサイズより大きければローテート
if ($sizeKb >= $this->logConfig->rotateSize) {
$this->runRotate($createdAt, $now);
}
}
/**
* ログ出力パスを返却する
* @return string ログ出力パス
*/
public function getLogPath()
{
return $this->logConfig->logPath;
}
/**
* ログローテートサイクルを返却する
* @return string ログ出力パス
*/
public function getLogRotateCycle()
{
return $this->logConfig->rotateCycle;
}
/**
* ログローテートサイズを返却する
* @return string ログ出力パス
*/
public function getLogRotateSize()
{
return $this->logConfig->rotateSize;
}
/**
* 遅延書き出しを有効にする
*/
public function lazyWrite()
{
foreach ($this->outputters as $outputter) {
if ($outputter instanceof ILazyWriter) {
$outputter->enableLazyWrite();
}
}
}
/**
* 即時書き出しを有効にする
*/
public function directWrite()
{
foreach ($this->outputters as $outputter) {
if ($outputter instanceof ILazyWriter) {
$outputter->enableDirectWrite();
}
}
}
}