/
Logger.php
433 lines (350 loc) · 11.3 KB
/
Logger.php
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<?php
namespace AllenJB\Utilities;
const CLI_NORMAL = "\033[0m";
const CLI_BLACK = "\033[0;30m";
const CLI_DGRAY = "\033[1;30m";
const CLI_BLUE = "\033[0;34m";
const CLI_LBLUE = "\033[1;34m";
const CLI_GREEN = "\033[0;32m";
const CLI_LGREEN = "\033[1;32m";
const CLI_CYAN = "\033[0;36m";
const CLI_LCYAN = "\033[1;36m";
const CLI_RED = "\033[0;31m";
const CLI_LRED = "\033[1;31m";
const CLI_PURPLE = "\033[0;35m";
const CLI_LPURPLE = "\033[1;35m";
const CLI_BROWN = "\033[0;33m";
const CLI_YELLOW = "\033[1;33m";
const CLI_LGRAY = "\033[0;37m";
const CLI_WHITE = "\033[1;37m";
const CLI_BG_BLACK = "\033[40m";
const CLI_BG_RED = "\033[41m";
const CLI_BG_GREEN = "\033[42m";
const CLI_BG_YELLOW = "\033[43m";
const CLI_BG_BLUE = "\033[44m";
const CLI_BG_MAGENTA = "\033[45m";
const CLI_BG_CYAN = "\033[46m";
const CLI_BG_LGRAY = "\033[47m";
class Logger
{
/**
* @var array All available log levels. The MUST be in order.
* Note: Keys and values are flipped by the constructor
*/
protected $levels = ['debug', 'info', 'warn', 'error', 'fatal'];
protected $levelColors = [
'debug' => CLI_LGRAY,
'info' => CLI_LGRAY,
'warn' => CLI_YELLOW,
'error' => CLI_LRED,
'fatal' => CLI_LRED,
];
/**
* @var int The current logging level
*/
protected $level = 0;
/**
* @var bool Log to the console?
*/
protected $logToConsole = true;
/**
* @var bool Log to disk?
*/
protected $logToDisk = true;
/**
* @var bool Log to memory (store log for later dump)?
*/
protected $logToMemory = false;
/**
* @var null|string Directory to store logs in
*/
protected $directory = null;
/**
* @var string String to append to the filename
*/
protected $filePart = '';
/**
* @var null|string Full filename, including path, of the file
*/
protected $file = null;
/**
* @var string Prefix to append to every log line
*/
protected $prefix = '';
/**
* @var string Date format used in the filename
*/
protected $fileDateFormat = 'Y-m-d_His';
/**
* @var string Date format used in log lines
*/
protected $lineDateFormat = 'Y-m-d H:i:s';
protected $colorsEnabled = false;
/**
* @var string[] In-memory log
*/
protected $memlog = [];
protected $progressLogging = false;
public function __construct()
{
// Flip levels, so that $this->levels[$level] gives us a number
$this->levels = array_flip($this->levels);
}
public function setEnableColors($enabled = true)
{
$this->colorsEnabled = $enabled;
}
public function setFilePart($part)
{
$this->filePart = $part;
if (is_string($this->directory) && ($this->directory !== "")) {
$this->updateFilename();
}
}
protected function updateFilename()
{
$file = '';
if (is_string($this->fileDateFormat) && (strlen($this->fileDateFormat) > 0)) {
$file .= date($this->fileDateFormat);
if (is_string($this->filePart) && (strlen($this->filePart) > 0)) {
$file .= '_';
}
}
if (is_string($this->filePart) && (strlen($this->filePart) > 0)) {
$file .= $this->filePart;
} else {
if (! (is_string($this->fileDateFormat) && (strlen($this->fileDateFormat) > 0))) {
$file .= 'current';
}
}
$this->file = $this->directory . $file . '.log';
}
public function setDirectory($dir)
{
$this->directory = rtrim($dir, '/') . '/';
if (! (file_exists($this->directory) && is_dir($this->directory))) {
$this->log("Creating log directory: {$this->directory}", 'info');
mkdir($this->directory, 0775, true);
}
$this->updateFilename();
if (! defined('ERROR_HANDLER_LOG')) {
define('ERROR_HANDLER_LOG', $this->file);
}
}
public function setLevel($level)
{
if (! array_key_exists($level, $this->levels)) {
throw new \InvalidArgumentException("Invalid log level specified: {$level}; Valid options are: "
. implode(array_keys($this->levels), ', '));
}
$this->level = $this->levels[$level];
$levels = array_flip($this->levels);
$this->log("Log Level set to: " . $levels[$this->level], 'info');
}
public function setPrefix($string = '')
{
if ((strlen($string) > 0) && (substr($string, -1) !== ' ')) {
$string .= ' ';
}
$this->prefix = $string;
}
/**
* @param string|null $format
*/
public function setFileDateFormat($format)
{
$this->fileDateFormat = $format;
if (is_string($this->directory) && ($this->directory !== "")) {
$this->updateFilename();
}
}
public function setLineDateFormat($format)
{
$this->lineDateFormat = $format;
}
public function init()
{
$this->log(str_repeat('-', 80), 'info');
$this->log("Logging to: {$this->file}", 'info');
}
public function log($msg, $level = 'info', $diskOnly = false)
{
if ($this->progressLogging && (! $diskOnly)) {
$this->logProgressEnd();
}
$logLevel = $this->levels[$level];
if ($this->level > $logLevel) {
return;
}
$levelTxt = str_pad(strtoupper($level), 5, ' ', STR_PAD_LEFT);
$date = $this->date();
if (is_string($date) && (strlen($date) > 0)) {
$date .= ' ';
}
$line = "{$date}{$levelTxt} {$this->prefix}{$msg} \n";
$consoleLine = $line;
if ($this->colorsEnabled) {
$consoleLine = $date . $this->levelColors[$level] . $levelTxt . CLI_NORMAL . " {$this->prefix}{$msg} \n";
}
if ($this->logToMemory) {
$this->memlog[] = $line;
}
if ($this->logToDisk && is_string($this->file) && ($this->file !== "")) {
if (file_exists($this->file) && (! is_writable($this->file))) {
$this->logToDisk = false;
trigger_error("Unable to write to log file - Log to disk has been FORCE DISABLED", E_USER_NOTICE);
} else {
file_put_contents($this->file, $line, FILE_APPEND);
}
}
if ($diskOnly) {
return;
}
if ($this->logToConsole) {
print $consoleLine;
}
}
/**
* Create a date/time stamp string in a specified format, using a method that makes resolutions lower than seconds
* work.
*
* We also have to make sure that there is a decimal point with numbers after it, otherwise the 'create from
* format' fails.
*
* @return bool|string
*/
protected function date()
{
$ts = number_format(microtime(true), 6, '.', '');
$dt = date_create_from_format("U.u", $ts);
if (! is_object($dt)) {
trigger_error(
"Failed to created timestamp for {$ts}: " . print_r(\DateTime::getLastErrors(), true),
E_USER_NOTICE
);
return date($this->lineDateFormat);
}
// DateTime objects created from timestamps are UTC by default - convert to the default tz
$dt->setTimezone(new \DateTimeZone(date_default_timezone_get()));
return $dt->format($this->lineDateFormat);
}
/**
* Log a progress message. This overwrites the previous contents of the current line on the console.
*
* @param String $msg Message to log
* @param string $level Log level
*/
public function logProgress($msg, $level = 'info')
{
$logLevel = $this->levels[$level];
if (! array_key_exists($level, $this->levels)) {
trigger_error("Invalid log level specified: {$level}", E_USER_NOTICE);
$logLevel = $this->levels[$level];
}
if ($this->level > $logLevel) {
return;
}
$this->log($msg, $level, true);
if ($this->logToConsole) {
$this->progressLogging = true;
$levelTxt = str_pad(strtoupper($level), 5, ' ', STR_PAD_LEFT);
$date = $this->date();
if (is_string($date) && (strlen($date) > 0)) {
$date .= ' ';
}
$line = $date . $this->levelColors[$level] . "{$levelTxt} {$this->prefix}{$msg} \n";
$consoleLine = $line;
if ($this->colorsEnabled) {
$consoleLine = $date . $this->levelColors[$level] . $levelTxt . CLI_NORMAL . " {$this->prefix}{$msg} \n";
}
$line = "\r\x1B[K" . trim($consoleLine) . CLI_NORMAL;
print $line;
}
}
/**
* End a section of progress log messages (move to next console line)
*/
public function logProgressEnd()
{
if ($this->logToConsole) {
print "\n";
$this->progressLogging = false;
}
}
protected function bytes_to_human($bytes)
{
$human = null;
if ($bytes < 1024) {
$human = number_format($bytes, 0) . ' bytes';
} else if ($bytes < 1024 * 1024) {
$human = number_format(($bytes / 1024), 1) . ' KB';
} else {
$human = number_format(($bytes / (1024 * 1024)), 1) . ' MB';
}
return $human;
}
public function logMemoryUsage()
{
$memUsageString = "";
if (function_exists('memory_get_usage')) {
$mem = memory_get_usage();
$mem_text = $this->bytes_to_human($mem);
$rmem = memory_get_usage(true);
$rmem_text = $this->bytes_to_human($rmem);
$memUsageString .= "Memory Usage: " . $mem_text . " / Real: " . $rmem_text . " :: ";
unset ($mem, $mem_text, $rmem, $rmem_text);
}
if (function_exists('memory_get_peak_usage')) {
$mem = $this->bytes_to_human(memory_get_peak_usage());
$rmem = $this->bytes_to_human(memory_get_peak_usage(true));
$memUsageString .= "Peak Mem Usage: " . $mem . " / Real: " . $rmem;
}
if ($memUsageString !== "") {
$this->log($memUsageString);
}
}
/**
* Is the specified level the same as or higher than 'error' (ie. does it include 'fatal' or anything else we come
* up with)
*
* @param string $level Error level to check
* @return bool
*/
public function isErrorLevel($level)
{
$logLevel = $this->levels[$level];
if ($this->level > $logLevel) {
trigger_error("Invalid log level: {$level}", E_USER_NOTICE);
return false;
}
return ($logLevel >= $this->levels['error']);
}
public function compress()
{
if ($this->file === null) {
return null;
}
exec("gzip -fq \"{$this->file}\"");
return $this->file . '.gz';
}
public function getFile()
{
return $this->file;
}
public function setLogToConsole($enabled = true)
{
$this->logToConsole = $enabled;
}
public function setLogToDisk($enabled = true)
{
$this->logToDisk = $enabled;
}
public function setLogToMemory($enabled = true)
{
$this->logToMemory = $enabled;
}
public function dumpLog()
{
return $this->memlog;
}
}