1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cronario\Logger; |
4
|
|
|
|
5
|
|
|
class Journal implements \Psr\Log\LoggerInterface |
6
|
|
|
{ |
7
|
|
|
use \Psr\Log\LoggerTrait; |
8
|
|
|
|
9
|
|
|
protected $journalFolder; |
10
|
|
|
protected $journalRecord; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @param string $folder |
14
|
|
|
* @param array $record |
15
|
|
|
*/ |
16
|
59 |
|
public function __construct($folder = __DIR__, array $record = ['emergency', 'alert', 'critical', 'error']) |
17
|
|
|
{ |
18
|
59 |
|
$this->journalFolder = rtrim($folder, '/') . '/'; |
19
|
59 |
|
$this->journalRecord = $record; |
20
|
59 |
|
} |
21
|
|
|
|
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param mixed $level |
25
|
|
|
* @param string $message |
26
|
|
|
* @param array $context |
27
|
|
|
* |
28
|
|
|
* @return null |
29
|
|
|
*/ |
30
|
1 |
|
public function log($level, $message, array $context = array()) |
31
|
|
|
{ |
32
|
|
|
|
33
|
1 |
|
if (!in_array($level, $this->journalRecord)) { |
34
|
1 |
|
return null; |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
$line = sprintf("%s: %s %s %s", |
38
|
1 |
|
$this->getCurrentDate(), |
39
|
1 |
|
str_repeat('. ', $this->levelToPoints[$level]), |
40
|
1 |
|
$message, |
41
|
1 |
|
'[ ' . implode(' ; ', $context) . ' ]' |
42
|
1 |
|
) . PHP_EOL; |
43
|
|
|
|
44
|
1 |
|
file_put_contents($this->getJournalPath(), $line, FILE_APPEND); |
45
|
|
|
|
46
|
1 |
|
return null; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @var array |
51
|
|
|
*/ |
52
|
|
|
protected $levelToPoints |
53
|
|
|
= [ |
54
|
|
|
'emergency' => 0, |
55
|
|
|
'alert' => 1, |
56
|
|
|
'critical' => 2, |
57
|
|
|
'error' => 3, |
58
|
|
|
'warning' => 4, |
59
|
|
|
'notice' => 5, |
60
|
|
|
'info' => 6, |
61
|
|
|
'debug' => 7, |
62
|
|
|
]; |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
1 |
|
protected function getCurrentDate() |
68
|
|
|
{ |
69
|
1 |
|
$t = microtime(true); |
70
|
1 |
|
$micro = sprintf("%06d", ($t - floor($t)) * 1000000); |
71
|
1 |
|
$d = new \DateTime(date('Y-m-d H:i:s.' . $micro, $t)); |
72
|
1 |
|
$result = $d->format('Y-m-d H:i:s.u'); |
73
|
|
|
|
74
|
1 |
|
return $result; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return string |
79
|
|
|
*/ |
80
|
1 |
|
protected function getJournalPath() |
81
|
|
|
{ |
82
|
1 |
|
return $this->journalFolder . date('Y-m-d') . '.log'; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
} |