CpeLogger::__construct()   B
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 20
nc 8
nop 3
1
<?php
2
3
namespace SA\CpeSdk;
4
5
use SA\CpeSdk;
6
7
/**
8
 * Allow formatted logging on STDOUT
9
 * Send logs to Syslog for log offloading
10
 */
11
class CpeLogger
12
{
13
    public $logPath;
14
    public $printout;
15
16
    // Exception
17
    const LOG_TYPE_ERROR = "LOG_TYPE_ERROR";
18
    const OPENLOG_ERROR  = "OPENLOG_ERROR";
19
20
    // Specify the path where to create the log files
21
    public function __construct(
22
        $logPath = null,
23
        $suffix = null, 
24
        $printout = false)
25
    {
26
        global $argv;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
27
28
        date_default_timezone_set('UTC');
29
        
30
        $this->printout = $printout;
31
        $this->logPath = "/var/tmp/logs/cpe/";
32
                
33
        if ($logPath)
34
            $this->logPath = $logPath;
35
36
        if (!file_exists($this->logPath))
37
            mkdir($this->logPath, 0755, true);
38
39
        $file = basename($argv[0]);
40
        if ($suffix)
41
            $file .= "-".$suffix;
42
        // Append progname to the path
43
        $this->logPath .= "/".$file.".log";
44
45
        $this->log_out(
46
            "INFO",
47
            "[CPE SDK] ".basename(__FILE__),
48
            "Logging to: ".$this->logPath);
49
    }
50
51
    // Log message to syslog and log file
52
    public function log_out(
53
        $type,
54
        $source,
55
        $message,
56
        $workflowId = null)
57
    {
58
        $log = [
59
            "time"    => date("Y-m-d H:i:s", time()),
60
            "source"  => $source,
61
            "type"    => $type,
62
            "message" => $message
63
        ];
64
    
65
        if ($workflowId)
66
            $log["workflowId"] = $workflowId;
67
68
        // Open Syslog. Use programe name as key
69
        if (!openlog (__FILE__, LOG_CONS|LOG_PID, LOG_LOCAL1))
70
            throw new CpeException("Unable to connect to Syslog!",
71
                OPENLOG_ERROR);
72
        
73
        // Change Syslog priority level
74
        switch ($type)
75
        {
76
        case "INFO":
77
            $priority = LOG_INFO;
78
            break;
79
        case "ERROR":
80
            $priority = LOG_ERR;
81
            break;
82
        case "FATAL":
83
            $priority = LOG_ALERT;
84
            break;
85
        case "WARNING":
86
            $priority = LOG_WARNING;
87
            break;
88
        case "DEBUG":
89
            $priority = LOG_DEBUG;
90
            break;
91
        default:
92
            throw new CpeException("Unknown log Type!", 
93
                LOG_TYPE_ERROR);
94
        }
95
        
96
        // Print log in file
97
        $this->print_to_file($log, $workflowId);
98
        
99
        // Encode log message in JSON for better parsing
100
        $out = json_encode($log);
101
        // Send to syslog
102
        syslog($priority, $out);
103
    }
104
105
    // Write log in file
106
    private function print_to_file($log, $workflowId)
107
    {
108
        if (!is_string($log['message']))
109
            $log['message'] = json_encode($log['message']);
110
        
111
        $toPrint = $log['time'] . " [" . $log['type'] . "] [" . $log['source'] . "] ";
112
        // If there is a workflow ID. We append it.
113
        if ($workflowId)
114
            $toPrint .= "[$workflowId] ";
115
        $toPrint .= $log['message'] . "\n";
116
117
        if ($this->printout)
118
            print $toPrint;
119
        
120
        if (file_put_contents(
121
                $this->logPath,
122
                $toPrint,
123
                FILE_APPEND) === false)
124
            print "ERROR: Can't write into log file!\n";
125
    }
126
}