Logger::log()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
ccs 6
cts 6
cp 1
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
namespace SixtyNine\Cloud\Factory;
4
5
use Monolog\Handler\ErrorLogHandler;
6
use Monolog\Handler\NullHandler;
7
use Monolog\Handler\StreamHandler;
8
use Monolog\Logger as MonologLogger;
9
10
class Logger
11
{
12
    const DEBUG = 100;
13
    const INFO = 200;
14
    const NOTICE = 250;
15
    const WARNING = 300;
16
    const ERROR = 400;
17
    const CRITICAL = 500;
18
    const ALERT = 550;
19
    const EMERGENCY = 600;
20
21
    /** @var Logger */
22
    protected static $instance;
23
    /** @var MonologLogger */
24
    protected $logger;
25
    /** @var string */
26
    protected $filename;
27
    /** @var bool */
28
    protected $outputChosen = false;
29
30
    /**
31
     * Disallow direct instantiation
32
     */
33 1
    protected function __construct()
34
    {
35 1
        $this->logger = new MonologLogger('log');
36 1
    }
37
38
    /**
39
     * @return Logger
40
     */
41 6
    public  static function getInstance()
42
    {
43 6
        if (!self::$instance) {
44 1
            self::$instance = new self();
45
        }
46 6
        return self::$instance;
47
    }
48
49
    /**
50
     * @return Logger
51
     */
52
    public function toConsole()
53
    {
54
        $this->outputChosen = true;
55
        $this->logger->pushHandler(new ErrorLogHandler());
56
        return $this;
57
    }
58
59
    /**
60
     * @param string $filename
61
     * @param int $level
62
     * @return Logger
63
     * @throws \InvalidArgumentException
64
     */
65
    public function toFile($filename, $level = MonologLogger::DEBUG)
66
    {
67
        if ($this->filename) {
68
            throw new \InvalidArgumentException('Log file already set');
69
        }
70
        $this->outputChosen = true;
71
        $this->logger->pushHandler(new StreamHandler($filename, $level));
72
        $this->filename = $filename;
73
        return $this;
74
    }
75
76
    /**
77
     * @param string $message
78
     * @param int $level
79
     * @param array $context
80
     */
81 6
    public function log($message, $level = MonologLogger::INFO, array $context = array())
82
    {
83 6
        if (!$this->outputChosen) {
84 1
            $this->outputChosen = true;
85 1
            $this->logger->pushHandler(new NullHandler());
86
        }
87 6
        $this->logger->log($level, $message, $context);
88 6
    }
89
90
    /**
91
     * @return MonologLogger
92
     */
93
    public function getLogger()
94
    {
95
        return $this->logger;
96
    }
97
}
98