Completed
Push — master ( 202314...8250e4 )
by Nate
02:58
created

LoggerTrait::loggerComponent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 13
cp 0
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 8
nop 0
crap 2
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 craft\log\FileTarget;
14
use yii\log\Dispatcher;
15
use yii\log\Logger;
16
17
/**
18
 * This trait will create and attach a separate log dispatcher / logger.  It allows modules to log to a separate
19
 * log file, while still supporting the use of categories.
20
 *
21
 * @author Flipbox Factory <[email protected]>
22
 * @since 1.0.2
23
 */
24
trait LoggerTrait
25
{
26
    /**
27
     * @var Logger|null
28
     */
29
    private static $_logger;
30
31
    /**
32
     * The log file name
33
     *
34
     * @return string
35
     */
36
    abstract protected static function getLogFileName(): string;
37
38
    /**
39
     * @inheritdoc
40
     */
41
    protected static function isDebugModeEnabled()
42
    {
43
        return false;
44
    }
45
46
    /**
47
     * @return Logger
48
     */
49
    public static function getLogger(): Logger
50
    {
51
        if (self::$_logger === null) {
52
            self::$_logger = static::resolveLogger();
53
        }
54
55
        return self::$_logger;
56
    }
57
58
    /**
59
     * @return Logger
60
     */
61
    protected static function resolveLogger(): Logger
62
    {
63
        try {
64
            $logger = Craft::createObject(static::loggerComponent());
65
66
            if ($logger instanceof Logger) {
67
                return $logger;
68
            }
69
        } catch (\Throwable $e) {
70
            Craft::error(
71
                'An exception was caught trying to create a logger: ' . $e->getMessage(),
72
                static::getLogFileName()
73
            );
74
        }
75
76
        return Craft::getLogger();
77
    }
78
79
    /**
80
     * @return \Closure
81
     */
82
    protected static function loggerComponent()
83
    {
84
        return function () {
85
            $dispatcher = Craft::createObject([
86
                'class' => Dispatcher::class,
87
                'logger' => new Logger(),
88
                'targets' => [
89
                    static::loggerFileTarget()
90
                ]
91
            ]);
92
93
            return $dispatcher->getLogger();
94
        };
95
    }
96
97
    /**
98
     * @return array
99
     */
100
    protected static function loggerFileTarget()
101
    {
102
        $generalConfig = Craft::$app->getConfig()->getGeneral();
103
104
        return [
105
            'class' => FileTarget::class,
106
            'fileMode' => $generalConfig->defaultFileMode,
107
            'dirMode' => $generalConfig->defaultDirMode,
108
            'logVars' => [],
109
            'levels' => array_merge(
110
                ['error', 'warning'],
111
                static::isDebugModeEnabled() ? ['trace', 'info'] : []
112
            ),
113
            'logFile' => '@storage/logs/' . self::prepLogFileName(static::getLogFileName())
114
        ];
115
    }
116
117
    /**
118
     * @param string $fileName
119
     * @return string
120
     */
121
    private static function prepLogFileName(string $fileName): string
122
    {
123
        return StringHelper::toKebabCase(
124
                StringHelper::removeRight($fileName, '.log')
125
            ) . '.log';
126
    }
127
128
    /**
129
     * Logs a debug message.
130
     * Trace messages are logged mainly for development purpose to see
131
     * the execution work flow of some code. This method will only log
132
     * a message when the application is in debug mode.
133
     * @param string|array $message the message to be logged. This can be a simple string or a more
134
     * complex data structure, such as array.
135
     * @param string $category the category of the message.
136
     * @since 2.0.14
137
     */
138
    public static function debug($message, $category = 'general')
139
    {
140
        static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
141
    }
142
143
    /**
144
     * Logs an error message.
145
     * An error message is typically logged when an unrecoverable error occurs
146
     * during the execution of an application.
147
     * @param string|array $message the message to be logged. This can be a simple string or a more
148
     * complex data structure, such as array.
149
     * @param string $category the category of the message.
150
     */
151
    public static function error($message, $category = 'general')
152
    {
153
        static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
154
    }
155
156
    /**
157
     * Logs a warning message.
158
     * A warning message is typically logged when an error occurs while the execution
159
     * can still continue.
160
     * @param string|array $message the message to be logged. This can be a simple string or a more
161
     * complex data structure, such as array.
162
     * @param string $category the category of the message.
163
     */
164
    public static function warning($message, $category = 'general')
165
    {
166
        static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
167
    }
168
169
    /**
170
     * Logs an informative message.
171
     * An informative message is typically logged by an application to keep record of
172
     * something important (e.g. an administrator logs in).
173
     * @param string|array $message the message to be logged. This can be a simple string or a more
174
     * complex data structure, such as array.
175
     * @param string $category the category of the message.
176
     */
177
    public static function info($message, $category = 'general')
178
    {
179
        static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
180
    }
181
}