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
|
<?php
use Katzgrau\KLogger\Logger;
use Psr\Log\LogLevel;
class LoggerTest extends PHPUnit\Framework\TestCase
{
private $logPath;
private $logger;
private $errLogger;
public function setUp()
{
$this->logPath = __DIR__.'/logs';
$this->logger = new Logger($this->logPath, LogLevel::DEBUG, array ('flushFrequency' => 1));
$this->errLogger = new Logger($this->logPath, LogLevel::ERROR, array (
'extension' => 'log',
'prefix' => 'error_',
'flushFrequency' => 1
));
}
public function testImplementsPsr3LoggerInterface()
{
$this->assertInstanceOf('Psr\Log\LoggerInterface', $this->logger);
}
public function testAcceptsExtension()
{
$this->assertStringEndsWith('.log', $this->errLogger->getLogFilePath());
}
public function testAcceptsPrefix()
{
$filename = basename($this->errLogger->getLogFilePath());
$this->assertStringStartsWith('error_', $filename);
}
public function testWritesBasicLogs()
{
$this->logger->log(LogLevel::DEBUG, 'This is a test');
$this->errLogger->log(LogLevel::ERROR, 'This is a test');
$this->assertTrue(file_exists($this->errLogger->getLogFilePath()));
$this->assertTrue(file_exists($this->logger->getLogFilePath()));
$this->assertLastLineEquals($this->logger);
$this->assertLastLineEquals($this->errLogger);
}
public function assertLastLineEquals(Logger $logr)
{
$this->assertEquals($logr->getLastLogLine(), $this->getLastLine($logr->getLogFilePath()));
}
public function assertLastLineNotEquals(Logger $logr)
{
$this->assertNotEquals($logr->getLastLogLine(), $this->getLastLine($logr->getLogFilePath()));
}
private function getLastLine($filename)
{
$size = filesize($filename);
$fp = fopen($filename, 'r');
$pos = -2; // start from second to last char
$t = ' ';
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
$t = fgetc($fp);
$pos = $pos - 1;
if ($size + $pos < -1) {
rewind($fp);
break;
}
}
$t = fgets($fp);
fclose($fp);
return trim($t);
}
public function tearDown() {
#@unlink($this->logger->getLogFilePath());
#@unlink($this->errLogger->getLogFilePath());
}
}
|