Completed
Push — feature/events ( 96fd77...b5e13c )
by Mathieu
02:04
created

Logger::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Suricate;
6
7
/**
8
 * Logger extension for Suricate
9
 *
10
 * @package Suricate\Cache
11
 * @author  Mathieu LESNIAK <[email protected]>
12
 *
13
 * @property string $logfile
14
 * @property boolean $enabled
15
 * @property int $level
16
 * @property boolean $timestamp
17
 */
18
class Logger extends Service
19
{
20
    const LOGLEVEL_FATAL = 0;
21
    const LOGLEVEL_ERROR = 1;
22
    const LOGLEVEL_WARN = 2;
23
    const LOGLEVEL_INFO = 3;
24
    const LOGLEVEL_DEBUG = 4;
25
26
    protected $parametersList = ['logfile', 'enabled', 'level', 'timestamp'];
27
28
    private $resource;
29
30
    protected $levels = [
31
        self::LOGLEVEL_FATAL => 'FATAL',
32
        self::LOGLEVEL_ERROR => 'ERROR',
33
        self::LOGLEVEL_WARN => 'WARN',
34
        self::LOGLEVEL_INFO => 'INFO',
35
        self::LOGLEVEL_DEBUG => 'DEBUG'
36
    ];
37
38 8
    public function __construct()
39
    {
40 8
        parent::__construct();
41 8
    }
42
43 2
    public function log($message, $level)
44
    {
45 2
        if ($this->resource == null && $this->logfile !== null) {
46 1
            $this->resource = fopen($this->logfile, 'a+');
47
        }
48
49 2
        if ($level <= $this->level && $this->enabled) {
50
            if ($this->timestamp) {
51
                $message = "[" . date('M d H:i:s') . "] " . $message;
52
            }
53
            fputs(
54
                $this->resource,
55
                '[' . $this->levels[$level] . '] ' . (string) $message . PHP_EOL
56
            );
57
        }
58
59 2
        return $this;
60
    }
61
62
    public function fatal($message)
63
    {
64
        return $this->log($message, self::LOGLEVEL_FATAL);
65
    }
66
67
    public function error($message)
68
    {
69
        return $this->log($message, self::LOGLEVEL_ERROR);
70
    }
71
72
    public function warn($message)
73
    {
74
        return $this->log($message, self::LOGLEVEL_WARN);
75
    }
76
77
    public function info($message)
78
    {
79
        return $this->log($message, self::LOGLEVEL_INFO);
80
    }
81
82 2
    public function debug($message)
83
    {
84 2
        return $this->log($message, self::LOGLEVEL_DEBUG);
85
    }
86
}
87