Passed
Push — master ( 7becb9...b5be1a )
by Biao
05:04
created

LogTrait::info()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Hhxsv5\LaravelS\Swoole\Traits;
4
5
use Hhxsv5\LaravelS\LaravelS;
6
7
trait LogTrait
8
{
9
    public function logException(\Exception $e)
10
    {
11
        $this->log(
12
            sprintf(
13
                'Uncaught exception \'%s\': [%d]%s called in %s:%d%s%s',
14
                get_class($e),
15
                $e->getCode(),
16
                $e->getMessage(),
17
                $e->getFile(),
18
                $e->getLine(),
19
                PHP_EOL,
20
                $e->getTraceAsString()
21
            ),
22
            'ERROR'
23
        );
24
    }
25
26
    public function log($msg, $type = 'INFO')
27
    {
28
        $outputStyle = LaravelS::getOutputStyle();
29
        if ($outputStyle) {
0 ignored issues
show
introduced by
$outputStyle is of type Symfony\Component\Console\Style\OutputStyle, thus it always evaluated to true.
Loading history...
30
            $msg = sprintf('[%s] %s', date('Y-m-d H:i:s'), $msg);
31
            switch (strtolower($type)) {
32
                case 'WARN':
33
                    $outputStyle->warning($msg);
34
                    break;
35
                case 'ERROR':
36
                    $outputStyle->error($msg);
37
                    break;
38
                default:
39
                    $outputStyle->note($msg);
40
                    break;
41
            }
42
        } else {
43
            $msg = sprintf('[%s] [%s] LaravelS: %s', date('Y-m-d H:i:s'), $type, $msg . PHP_EOL);
44
            echo $msg;
45
        }
46
    }
47
48
    public function info($msg)
49
    {
50
        $this->log($msg, 'INFO');
51
    }
52
53
    public function warning($msg)
54
    {
55
        $this->log($msg, 'WARN');
56
    }
57
58
    public function error($msg)
59
    {
60
        $this->log($msg, 'ERROR');
61
    }
62
63
64
    public function callWithCatchException(callable $callback)
65
    {
66
        try {
67
            return $callback();
68
        } catch (\Exception $e) {
69
            $this->logException($e);
70
            return false;
71
        }
72
    }
73
}