1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Hhxsv5\LaravelS\Swoole\Traits; |
4
|
|
|
|
5
|
|
|
use Hhxsv5\LaravelS\LaravelS; |
6
|
|
|
use Symfony\Component\Console\Formatter\OutputFormatterStyle; |
7
|
|
|
|
8
|
|
|
trait LogTrait |
9
|
|
|
{ |
10
|
|
|
public function logException(\Exception $e) |
11
|
|
|
{ |
12
|
|
|
$this->log( |
13
|
|
|
sprintf( |
14
|
|
|
'Uncaught exception \'%s\': [%d]%s called in %s:%d%s%s', |
15
|
|
|
get_class($e), |
16
|
|
|
$e->getCode(), |
17
|
|
|
$e->getMessage(), |
18
|
|
|
$e->getFile(), |
19
|
|
|
$e->getLine(), |
20
|
|
|
PHP_EOL, |
21
|
|
|
$e->getTraceAsString() |
22
|
|
|
), |
23
|
|
|
'ERROR' |
24
|
|
|
); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function log($msg, $type = 'INFO') |
28
|
|
|
{ |
29
|
|
|
$outputStyle = LaravelS::getOutputStyle(); |
30
|
|
|
$msg = sprintf('[%s] [%s] %s', date('Y-m-d H:i:s'), $type, $msg); |
31
|
|
|
if ($outputStyle) { |
|
|
|
|
32
|
|
|
switch (strtoupper($type)) { |
33
|
|
|
case 'WARN': |
34
|
|
|
if (!$outputStyle->getFormatter()->hasStyle('warning')) { |
35
|
|
|
$style = new OutputFormatterStyle('yellow'); |
36
|
|
|
$outputStyle->getFormatter()->setStyle('warning', $style); |
37
|
|
|
} |
38
|
|
|
$outputStyle->writeln("<warning>$msg</warning>"); |
39
|
|
|
break; |
40
|
|
|
case 'ERROR': |
41
|
|
|
$outputStyle->writeln("<error>$msg</error>"); |
42
|
|
|
break; |
43
|
|
|
case 'INFO': |
44
|
|
|
$outputStyle->writeln("<info>$msg</info>"); |
45
|
|
|
break; |
46
|
|
|
default: |
47
|
|
|
$outputStyle->writeln($msg); |
48
|
|
|
break; |
49
|
|
|
} |
50
|
|
|
} else { |
51
|
|
|
echo $msg, PHP_EOL; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function info($msg) |
56
|
|
|
{ |
57
|
|
|
$this->log($msg, 'INFO'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function warning($msg) |
61
|
|
|
{ |
62
|
|
|
$this->log($msg, 'WARN'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function error($msg) |
66
|
|
|
{ |
67
|
|
|
$this->log($msg, 'ERROR'); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
|
71
|
|
|
public function callWithCatchException(callable $callback) |
72
|
|
|
{ |
73
|
|
|
try { |
74
|
|
|
return $callback(); |
75
|
|
|
} catch (\Exception $e) { |
76
|
|
|
$this->logException($e); |
77
|
|
|
return false; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |