Passed
Push — master ( 1e4b3a...3c3497 )
by Ioannes
01:26
created

Log   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Importance

Changes 9
Bugs 1 Features 1
Metric Value
wmc 43
eloc 92
c 9
b 1
f 1
dl 0
loc 234
rs 8.96

15 Methods

Rating   Name   Duplication   Size   Complexity  
A emergency() 0 8 2
A formatMessage() 0 9 5
A cleanLogs() 0 6 2
A telegram() 0 11 3
A error() 0 9 3
A logInnerException() 0 3 1
A __construct() 0 6 3
A alert() 0 8 2
A notice() 0 9 3
A critical() 0 8 2
A isDebugEnabled() 0 16 5
A warning() 0 9 3
A log() 0 9 3
A debug() 0 9 3
A info() 0 9 3

How to fix   Complexity   

Complex Class

Complex classes like Log often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Log, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace App;
3
4
use App\Monolog\LoggerFactory;
5
use Bitrix\Main\Diag\Debug;
0 ignored issues
show
Bug introduced by
The type Bitrix\Main\Diag\Debug was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Bitrix\Main\Error;
0 ignored issues
show
Bug introduced by
The type Bitrix\Main\Error was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Monolog\Logger;
8
use Psr\Log\LoggerInterface;
9
use Psr\Log\LogLevel;
10
11
class Log implements LoggerInterface {
12
13
    private $channel;
14
15
    /**
16
     * @param string $channel
17
     */
18
    public function __construct($channel = '') {
19
20
        if(!empty($channel)) {
21
            $this->channel = $channel;
22
        } else {
23
            $this->channel = ($_ENV['APP_LOG_BITRIX_CHANNEL'] ?: 'bitrix');
24
        }
25
    }
26
27
    /**
28
     * @param mixed $message
29
     * @param array $context
30
     */
31
    public function alert($message, $context = [])
32
    {
33
        try {
34
            $logger = LoggerFactory::getInstance($this->channel, $context);
35
            $message = $this->formatMessage($message);
36
            $logger->alert($message, (array) $context);
37
        } catch (\Exception $e) {
38
            $this->logInnerException($e);
39
        }
40
    }
41
42
    /**
43
     * @param mixed $message
44
     * @param array $context
45
     */
46
    public function critical($message, $context = [])
47
    {
48
        try {
49
            $logger = LoggerFactory::getInstance($this->channel, $context);
50
            $message = $this->formatMessage($message);
51
            $logger->critical($message, (array) $context);
52
        } catch (\Exception $e) {
53
            $this->logInnerException($e);
54
        }
55
    }
56
57
    /**
58
     * @param mixed $message
59
     * @param array $context
60
     */
61
    public function error($message, $context = [])
62
    {
63
        if ($this->isDebugEnabled(Logger::ERROR)) {
64
            try {
65
                $logger = LoggerFactory::getInstance($this->channel, $context);
66
                $message = $this->formatMessage($message);
67
                $logger->error($message, (array) $context);
68
            } catch (\Exception $e) {
69
                $this->logInnerException($e);
70
            }
71
        }
72
    }
73
74
    /**
75
     * @param mixed $message
76
     * @param array $context
77
     */
78
    public function warning($message, $context = [])
79
    {
80
        if ($this->isDebugEnabled(Logger::WARNING)) {
81
            try {
82
                $logger = LoggerFactory::getInstance($this->channel, $context);
83
                $message = $this->formatMessage($message);
84
                $logger->warning($message, (array) $context);
85
            } catch (\Exception $e) {
86
                $this->logInnerException($e);
87
            }
88
        }
89
    }
90
91
    /**
92
     * @param mixed $message
93
     * @param array $context
94
     */
95
    public function notice($message, $context = [])
96
    {
97
        if ($this->isDebugEnabled(Logger::NOTICE)) {
98
            try {
99
                $logger = LoggerFactory::getInstance($this->channel, $context);
100
                $message = $this->formatMessage($message);
101
                $logger->notice($message, (array) $context);
102
            } catch (\Exception $e) {
103
                $this->logInnerException($e);
104
            }
105
        }
106
    }
107
108
    /**
109
     * @param mixed $message
110
     * @param array $context
111
     */
112
    public function info($message, $context = [])
113
    {
114
        if ($this->isDebugEnabled(Logger::INFO)) {
115
            try {
116
                $logger = LoggerFactory::getInstance($this->channel, $context);
117
                $message = $this->formatMessage($message);
118
                $logger->info($message, (array) $context);
119
            } catch (\Exception $e) {
120
                $this->logInnerException($e);
121
            }
122
        }
123
    }
124
125
    /**
126
     * @param mixed $message
127
     * @param array $context
128
     */
129
    public function debug($message, $context = [])
130
    {
131
        if ($this->isDebugEnabled(Logger::DEBUG)) {
132
            try {
133
                $logger = LoggerFactory::getInstance($this->channel, $context);
134
                $message = $this->formatMessage($message);
135
                $logger->debug($message, (array) $context);
136
            } catch (\Exception $e) {
137
                $this->logInnerException($e);
138
            }
139
        }
140
    }
141
142
    /**
143
     * @param mixed $message
144
     * @param array $context
145
     */
146
    public function emergency($message, $context = [])
147
    {
148
        try {
149
            $logger = LoggerFactory::getInstance($this->channel, $context);
150
            $message = $this->formatMessage($message);
151
            $logger->emergency($message, (array) $context);
152
        } catch (\Exception $e) {
153
            $this->logInnerException($e);
154
        }
155
    }
156
157
    /**
158
     * @param mixed $level
159
     * @param mixed $message
160
     * @param array $context
161
     */
162
    public function log($level, $message, $context = [])
163
    {
164
        if ($this->isDebugEnabled($level)) {
165
            try {
166
                $logger = LoggerFactory::getInstance($this->channel, $context);
167
                $message = $this->formatMessage($message);
168
                $logger->log($level, $message, (array) $context);
169
            } catch (\Exception $e) {
170
                $this->logInnerException($e);
171
            }
172
        }
173
    }
174
175
    /**
176
     * @param mixed $level
177
     * @param mixed $message
178
     * @param array $context
179
     */
180
    public function telegram($level, $message, $context = []) {
181
182
        $level = Logger::toMonologLevel($level);
183
        if (!$this->isDebugEnabled($level)) {
184
            return;
185
        }
186
187
        $logger = LoggerFactory::getInstance('telegram-messenger', $context);
188
189
        if($logger) {
190
            $logger->log($level, $message, $context);
191
        }
192
    }
193
194
    /**
195
     * @param mixed $message
196
     * @return string
197
     */
198
    private function formatMessage($message) {
199
200
        if($message instanceof \Exception || $message instanceof Error) {
201
            $message = (string) $message;
202
        } else if(is_array($message) || is_object($message)) {
203
            $message = json_encode((array) $message, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
204
            $message = str_replace('\\u0000', '', $message);
205
        }
206
        return (string) $message;
207
    }
208
209
    /**
210
     * @param mixed $level
211
     * @return bool
212
     */
213
    private function isDebugEnabled($level)
214
    {
215
        if (defined('FORCE_DEBUG') && FORCE_DEBUG) {
0 ignored issues
show
Bug introduced by
The constant App\FORCE_DEBUG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
216
            return true;
217
        }
218
219
        $level = Logger::toMonologLevel($level);
220
221
        $levels = Logger::getLevels();
0 ignored issues
show
Unused Code introduced by
The assignment to $levels is dead and can be removed.
Loading history...
222
        $minDebugLevel = ($_ENV['APP_DEBUG_LEVEL'] ?: LogLevel::DEBUG);
223
        $minDebugLevel = Logger::toMonologLevel($minDebugLevel);
224
225
        if($level >= $minDebugLevel) {
226
            return true;
227
        }
228
        return false;
229
    }
230
231
    /**
232
     * @param \Exception $exception
233
     */
234
    protected function logInnerException(\Exception $exception)
235
    {
236
        Debug::writeToFile((string) $exception, "", "inner_error.log");
237
    }
238
239
    public static function cleanLogs($daysAgo = 15) {
240
241
        $logPath = $_SERVER['DOCUMENT_ROOT'] . ($_ENV['APP_LOG_FOLDER'] ?: '/log/');
242
        $command = sprintf("find %s -mindepth 1 -type f -mtime +%d | xargs rm", $logPath, $daysAgo);
243
        exec($command);
244
        return sprintf('\App\Log::cleanLogs(%d);', $daysAgo);
245
    }
246
}
247