Completed
Push — 6.0 ( e4824c...eb454a )
by liu
04:59
created

File::getDebugLog()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 19
nc 6
nop 3
dl 0
loc 30
ccs 0
cts 19
cp 0
crap 56
rs 8.8333
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think\log\driver;
14
15
use think\App;
16
use think\contract\LogHandlerInterface;
17
18
/**
19
 * 本地化调试输出到文件
20
 */
21
class File implements LogHandlerInterface
22
{
23
    /**
24
     * 配置参数
25
     * @var array
26
     */
27
    protected $config = [
28
        'time_format' => 'c',
29
        'single'      => false,
30
        'file_size'   => 2097152,
31
        'path'        => '',
32
        'apart_level' => [],
33
        'max_files'   => 0,
34
        'json'        => false,
35
    ];
36
37
    /**
38
     * 应用对象
39
     * @var App
40
     */
41
    protected $app;
42
43
    /**
44
     * 是否控制台执行
45
     * @var bool
46
     */
47
    protected $isCli = false;
48
49
    // 实例化并传入参数
50
    public function __construct(App $app, $config = [])
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
51
    {
52
        $this->app = $app;
53
54
        if (is_array($config)) {
55
            $this->config = array_merge($this->config, $config);
56
        }
57
58
        $this->isCli = $app->runningInConsole();
59
    }
60
61
    /**
62
     * 日志写入接口
63
     * @access public
64
     * @param  array $log 日志信息
65
     * @return bool
66
     */
67
    public function save(array $log): bool
68
    {
69
        $destination = $this->getMasterLogFile();
70
71
        $path = dirname($destination);
72
        !is_dir($path) && mkdir($path, 0755, true);
73
74
        $info = [];
75
76
        foreach ($log as $type => $val) {
77
78
            foreach ($val as $msg) {
79
                if (!is_string($msg)) {
80
                    $msg = var_export($msg, true);
81
                }
82
83
                $info[$type][] = $this->config['json'] ? $msg : '[ ' . $type . ' ] ' . $msg;
84
            }
85
86
            if (!$this->config['json'] && (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level']))) {
87
                // 独立记录的日志级别
88
                $filename = $this->getApartLevelFile($path, $type);
89
90
                $this->write($info[$type], $filename, true);
91
92
                unset($info[$type]);
93
            }
94
        }
95
96
        if ($info) {
97
            return $this->write($info, $destination, false);
98
        }
99
100
        return true;
101
    }
102
103
    /**
104
     * 日志写入
105
     * @access protected
106
     * @param  array  $message 日志信息
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
107
     * @param  string $destination 日志文件
108
     * @param  bool   $apart 是否独立文件写入
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
109
     * @return bool
110
     */
111
    protected function write(array $message, string $destination, bool $apart = false): bool
0 ignored issues
show
Unused Code introduced by
The parameter $apart is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

111
    protected function write(array $message, string $destination, /** @scrutinizer ignore-unused */ bool $apart = false): bool

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
112
    {
113
        // 检测日志文件大小,超过配置大小则备份日志文件重新生成
114
        $this->checkLogSize($destination);
115
116
        $info = [];
117
        // 日志信息封装
118
        $info['timestamp'] = date($this->config['time_format']);
119
120
        foreach ($message as $type => $msg) {
121
            $info[$type] = is_array($msg) ? implode(PHP_EOL, $msg) : $msg;
122
        }
123
124
        if ($this->isCli) {
125
            $message = $this->parseCliLog($info);
126
        } else {
127
            $message = $this->parseLog($info);
128
        }
129
130
        return error_log($message, 3, $destination);
131
    }
132
133
    /**
134
     * 获取主日志文件名
135
     * @access public
136
     * @return string
137
     */
138
    protected function getMasterLogFile(): string
139
    {
140
        if (empty($this->config['path'])) {
141
            $this->config['path'] = $this->app->getRuntimePath() . 'log' . DIRECTORY_SEPARATOR;
142
        } elseif (substr($this->config['path'], -1) != DIRECTORY_SEPARATOR) {
143
            $this->config['path'] .= DIRECTORY_SEPARATOR;
144
        }
145
146
        if ($this->config['max_files']) {
147
            $files = glob($this->config['path'] . '*.log');
148
149
            try {
150
                if (count($files) > $this->config['max_files']) {
0 ignored issues
show
Bug introduced by
It seems like $files can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

150
                if (count(/** @scrutinizer ignore-type */ $files) > $this->config['max_files']) {
Loading history...
151
                    unlink($files[0]);
152
                }
153
            } catch (\Exception $e) {
154
                //
155
            }
156
        }
157
158
        if ($this->config['single']) {
159
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';
160
161
            $destination = $this->config['path'] . $name . '.log';
162
        } else {
163
            $cli = $this->isCli ? '_cli' : '';
164
165
            if ($this->config['max_files']) {
166
                $filename = date('Ymd') . $cli . '.log';
167
            } else {
168
                $filename = date('Ym') . DIRECTORY_SEPARATOR . date('d') . $cli . '.log';
169
            }
170
171
            $destination = $this->config['path'] . $filename;
172
        }
173
174
        return $destination;
175
    }
176
177
    /**
178
     * 获取独立日志文件名
179
     * @access public
180
     * @param  string $path 日志目录
181
     * @param  string $type 日志类型
182
     * @return string
183
     */
184
    protected function getApartLevelFile(string $path, string $type): string
185
    {
186
        $cli = $this->isCli ? '_cli' : '';
187
188
        if ($this->config['single']) {
189
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';
190
191
            $name .= '_' . $type;
192
        } elseif ($this->config['max_files']) {
193
            $name = date('Ymd') . '_' . $type . $cli;
194
        } else {
195
            $name = date('d') . '_' . $type . $cli;
196
        }
197
198
        return $path . DIRECTORY_SEPARATOR . $name . '.log';
199
    }
200
201
    /**
202
     * 检查日志文件大小并自动生成备份文件
203
     * @access protected
204
     * @param  string $destination 日志文件
205
     * @return void
206
     */
207
    protected function checkLogSize(string $destination): void
208
    {
209
        if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
210
            try {
211
                rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination));
212
            } catch (\Exception $e) {
213
                //
214
            }
215
        }
216
    }
217
218
    /**
219
     * CLI日志解析
220
     * @access protected
221
     * @param  array $info 日志信息
222
     * @return string
223
     */
224
    protected function parseCliLog(array $info): string
225
    {
226
        if ($this->config['json']) {
227
            $message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
228
        } else {
229
            $now = $info['timestamp'];
230
            unset($info['timestamp']);
231
232
            $message = implode(PHP_EOL, $info);
233
234
            $message = "[{$now}]" . $message . PHP_EOL;
235
        }
236
237
        return $message;
238
    }
239
240
    /**
241
     * 解析日志
242
     * @access protected
243
     * @param  array $info 日志信息
244
     * @return string
245
     */
246
    protected function parseLog(array $info): string
247
    {
248
        $requestInfo = [
249
            'ip'     => $this->app->request->ip(),
250
            'method' => $this->app->request->method(),
251
            'host'   => $this->app->request->host(),
252
            'uri'    => $this->app->request->url(),
253
        ];
254
255
        if ($this->config['json']) {
256
            $info = $requestInfo + $info;
257
            return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
258
        }
259
260
        array_unshift($info, "---------------------------------------------------------------" . PHP_EOL . "[{$info['timestamp']}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}");
261
        unset($info['timestamp']);
262
263
        return implode(PHP_EOL, $info) . PHP_EOL;
264
    }
265
266
}
267