1
|
|
|
<?php |
2
|
|
|
namespace WebServCo\Framework; |
3
|
|
|
|
4
|
|
|
use WebServCo\Framework\Interfaces\RequestInterface; |
5
|
|
|
use WebServCo\Framework\Exceptions\ApplicationException; |
6
|
|
|
|
7
|
|
|
final class FileLogger implements \WebServCo\Framework\Interfaces\LoggerInterface |
8
|
|
|
{ |
9
|
|
|
protected $channel; |
10
|
|
|
protected $logPath; |
11
|
|
|
protected $requestInterface; |
12
|
|
|
|
13
|
|
|
public function __construct($channel, $logDir, RequestInterface $requestInterface) |
14
|
|
|
{ |
15
|
|
|
$this->channel = $channel; |
16
|
|
|
|
17
|
|
|
if (!is_readable($logDir)) { |
18
|
|
|
throw new ApplicationException('Log dir not readable'); |
19
|
|
|
} |
20
|
|
|
if (!is_writable($logDir)) { |
21
|
|
|
throw new ApplicationException('Log dir not writeable'); |
22
|
|
|
} |
23
|
|
|
$this->logPath = sprintf('%s%s.log', $logDir, $this->channel); |
24
|
|
|
|
25
|
|
|
$this->requestInterface = $requestInterface; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function debug($message, $context = []) |
29
|
|
|
{ |
30
|
|
|
return $this->log(\WebServCo\Framework\LogLevel::DEBUG, $message, $context); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function error($message, $context = []) |
34
|
|
|
{ |
35
|
|
|
return $this->log(\WebServCo\Framework\LogLevel::ERROR, $message, $context); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function log($level, $message, $context = []) |
39
|
|
|
{ |
40
|
|
|
$data = sprintf( |
41
|
|
|
'[%s] [%s] [%s] %s%s', |
42
|
|
|
date('Y-m-d H:i:s'), |
43
|
|
|
$this->requestInterface->getRemoteAddress(), |
44
|
|
|
$level, |
45
|
|
|
$message, |
46
|
|
|
PHP_EOL |
47
|
|
|
); |
48
|
|
|
if (!empty($context)) { |
49
|
|
|
$data .= sprintf('%s%s', var_export($context, true), PHP_EOL); |
50
|
|
|
} |
51
|
|
|
return file_put_contents($this->logPath, $data, FILE_APPEND); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function clear() |
55
|
|
|
{ |
56
|
|
|
return file_put_contents($this->logPath, null); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|