LogFormatterFactory.php
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
/**
* @author:wlj
* @date: 2022/6/7 16:49
*/
namespace App\Factory;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class LogFormatterFactory
{
/**
* 实现日志工厂
*
* @param array $config /config/logging.php 当前频道的配置
* @return \Monolog\Logger
*/
public function __invoke(array $config)
{
return new Logger('', [
$this->create($config, Logger::ERROR, 'errors'),
$this->create($config, Logger::INFO, 'info'),
]);
}
private function create($config, $level, $suffix = '')
{
$time = time();
$path = date('Y-m', $time) . '/' . date('d', $time) . '_' . $suffix . '.log';
$path = 'logs/' . $config['prefix'] . '/' . $path;
$path = storage_path($path);
try {
if (!file_exists($path)) {
$directory = pathinfo($path, PATHINFO_DIRNAME);
if(!file_exists($directory)){
mkdir($directory, 0755, true);
chown($directory, 'www');
}
touch($path);
chown($path, 'www');
}
}catch (\Throwable $exception){}
$handler = new StreamHandler($path, $level, false);
$handler->setFormatter(new LineFormatter(null, 'Y-m-d H:i:s', false, true));
return $handler;
}
}