Completed
Push — develop ( 7779bb...64bf16 )
by Nate
03:49
created

LoggerTrait::getLogFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
nc 1
cc 1
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 string
48
     */
49
    public static function getLogFile(): string
50
    {
51
        return '@storage/logs/' . self::prepLogFileName(static::getLogFileName());
52
    }
53
54
    /**
55
     * @return Logger
56
     */
57
    public static function getLogger(): Logger
58
    {
59
        if (self::$logger === null) {
60
            self::$logger = static::resolveLogger();
61
        }
62
63
        return self::$logger;
64
    }
65
66
    /**
67
     * @return Logger
68
     */
69
    protected static function resolveLogger(): Logger
70
    {
71
        try {
72
            $logger = Craft::createObject(static::loggerComponent());
73
74
            if ($logger instanceof Logger) {
75
                return $logger;
76
            }
77
        } catch (\Throwable $e) {
78
            Craft::error(
79
                'An exception was caught trying to create a logger: ' . $e->getMessage(),
80
                static::getLogFileName()
81
            );
82
        }
83
84
        return Craft::getLogger();
85
    }
86
87
    /**
88
     * @return \Closure
89
     */
90
    protected static function loggerComponent()
91
    {
92
        return function () {
93
            $dispatcher = Craft::createObject([
94
                'class' => Dispatcher::class,
95
                'logger' => new Logger(),
96
                'targets' => [
97
                    static::loggerFileTarget()
98
                ]
99
            ]);
100
101
            return $dispatcher->getLogger();
102
        };
103
    }
104
105
    /**
106
     * @return array
107
     */
108
    protected static function loggerFileTarget()
109
    {
110
        $generalConfig = Craft::$app->getConfig()->getGeneral();
111
112
        return [
113
            'class' => FileTarget::class,
114
            'fileMode' => $generalConfig->defaultFileMode,
115
            'dirMode' => $generalConfig->defaultDirMode,
116
            'logVars' => [],
117
            'levels' => array_merge(
118
                ['error', 'warning'],
119
                (static::isDebugModeEnabled() || YII_DEBUG) ? ['trace', 'info'] : []
120
            ),
121
            'logFile' => static::getLogFile()
122
        ];
123
    }
124
125
    /**
126
     * @param string $fileName
127
     * @return string
128
     */
129
    private static function prepLogFileName(string $fileName): string
130
    {
131
        return StringHelper::toKebabCase(
132
            StringHelper::removeRight($fileName, '.log')
133
        ) . '.log';
134
    }
135
136
    /**
137
     * Logs a debug message.
138
     * Trace messages are logged mainly for development purpose to see
139
     * the execution work flow of some code. This method will only log
140
     * a message when the application is in debug mode.
141
     * @param string|array $message the message to be logged. This can be a simple string or a more
142
     * complex data structure, such as array.
143
     * @param string $category the category of the message.
144
     * @since 2.0.14
145
     */
146
    public static function debug($message, $category = 'general')
147
    {
148
        static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
149
    }
150
151
    /**
152
     * Logs an error message.
153
     * An error message is typically logged when an unrecoverable error occurs
154
     * during the execution of an application.
155
     * @param string|array $message the message to be logged. This can be a simple string or a more
156
     * complex data structure, such as array.
157
     * @param string $category the category of the message.
158
     */
159
    public static function error($message, $category = 'general')
160
    {
161
        static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
162
    }
163
164
    /**
165
     * Logs a warning message.
166
     * A warning message is typically logged when an error occurs while the execution
167
     * can still continue.
168
     * @param string|array $message the message to be logged. This can be a simple string or a more
169
     * complex data structure, such as array.
170
     * @param string $category the category of the message.
171
     */
172
    public static function warning($message, $category = 'general')
173
    {
174
        static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
175
    }
176
177
    /**
178
     * Logs an informative message.
179
     * An informative message is typically logged by an application to keep record of
180
     * something important (e.g. an administrator logs in).
181
     * @param string|array $message the message to be logged. This can be a simple string or a more
182
     * complex data structure, such as array.
183
     * @param string $category the category of the message.
184
     */
185
    public static function info($message, $category = 'general')
186
    {
187
        static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
188
    }
189
}
190