Completed
Push — develop ( b18ff4...7eaa04 )
by Nate
02:34
created

LoggerTrait::resolveLogger()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 0
cts 15
cp 0
rs 9.4285
c 0
b 0
f 0
nc 3
cc 3
eloc 10
nop 0
crap 12
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember
7
 */
8
9
namespace flipbox\ember\modules;
10
11
use Craft;
12
use craft\helpers\StringHelper;
13
use yii\log\Dispatcher;
14
use yii\log\Logger;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 1.0.2
19
 */
20
trait LoggerTrait
21
{
22
    /**
23
     * @var Logger|null
24
     */
25
    private static $_logger;
26
27
    /**
28
     * The log file name
29
     *
30
     * @return string
31
     */
32
    abstract protected static function getLogFileName(): string;
33
34
    /**
35
     * @inheritdoc
36
     */
37
    public static function isDebugModeEnabled()
38
    {
39
        return false;
40
    }
41
42
    /**
43
     * @return Logger
44
     */
45
    public static function getLogger(): Logger
46
    {
47
        if (self::$_logger === null) {
48
            self::$_logger = static::resolveLogger();
49
        }
50
51
        return self::$_logger;
52
    }
53
54
    /**
55
     * @return Logger
56
     */
57
    protected static function resolveLogger(): Logger
58
    {
59
        try {
60
            $logger = Craft::createObject(static::loggerComponent());
61
62
            if ($logger instanceof Logger) {
63
                return $logger;
64
            }
65
        } catch (\Throwable $e) {
1 ignored issue
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
66
            Craft::error(
67
                'An exception was caught trying to create a logger: ' . $e->getMessage(),
68
                static::getLogFileName()
69
            );
70
        }
71
72
        return Craft::getLogger();
73
    }
74
75
    /**
76
     * @return \Closure
77
     */
78
    protected static function loggerComponent()
79
    {
80
        return function () {
81
            $dispatcher = Craft::createObject([
82
                'class' => Dispatcher::class,
83
                'logger' => new Logger(),
84
                'targets' => [
85
                    static::loggerFileTarget()
86
                ]
87
            ]);
88
89
            return $dispatcher->getLogger();
90
        };
91
    }
92
93
    /**
94
     * @return array
95
     */
96
    protected static function loggerFileTarget()
97
    {
98
        $generalConfig = Craft::$app->getConfig()->getGeneral();
99
100
        return [
101
            'class' => craft\log\FileTarget::class,
102
            'fileMode' => $generalConfig->defaultFileMode,
103
            'dirMode' => $generalConfig->defaultDirMode,
104
            'logVars' => [],
105
            'levels' => array_merge(
106
                ['error', 'warning'],
107
                static::isDebugModeEnabled() ? ['trace', 'info'] : []
108
            ),
109
            'logFile' => '@storage/logs/' .
110
                StringHelper::toKebabCase(
111
                    StringHelper::removeRight(static::getLogFileName(), '.log')
112
                ) . '.log'
113
        ];
114
    }
115
116
    /**
117
     * Logs a debug message.
118
     * Trace messages are logged mainly for development purpose to see
119
     * the execution work flow of some code. This method will only log
120
     * a message when the application is in debug mode.
121
     * @param string|array $message the message to be logged. This can be a simple string or a more
122
     * complex data structure, such as array.
123
     * @param string $category the category of the message.
124
     * @since 2.0.14
125
     */
126
    public static function debug($message, $category = 'general')
127
    {
128
        static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
129
    }
130
131
    /**
132
     * Logs an error message.
133
     * An error message is typically logged when an unrecoverable error occurs
134
     * during the execution of an application.
135
     * @param string|array $message the message to be logged. This can be a simple string or a more
136
     * complex data structure, such as array.
137
     * @param string $category the category of the message.
138
     */
139
    public static function error($message, $category = 'general')
140
    {
141
        static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
142
    }
143
144
    /**
145
     * Logs a warning message.
146
     * A warning message is typically logged when an error occurs while the execution
147
     * can still continue.
148
     * @param string|array $message the message to be logged. This can be a simple string or a more
149
     * complex data structure, such as array.
150
     * @param string $category the category of the message.
151
     */
152
    public static function warning($message, $category = 'general')
153
    {
154
        static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
155
    }
156
157
    /**
158
     * Logs an informative message.
159
     * An informative message is typically logged by an application to keep record of
160
     * something important (e.g. an administrator logs in).
161
     * @param string|array $message the message to be logged. This can be a simple string or a more
162
     * complex data structure, such as array.
163
     * @param string $category the category of the message.
164
     */
165
    public static function info($message, $category = 'general')
166
    {
167
        static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
168
    }
169
}