-
-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathStreamLogger.php
More file actions
74 lines (60 loc) · 1.76 KB
/
StreamLogger.php
File metadata and controls
74 lines (60 loc) · 1.76 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/**
* This file is part of the Tracy (https://tracy.nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Tracy;
/**
* Logger which writes to a file.
*/
class StreamLogger implements ILogger
{
/** @var string path to a file where errors should be logged */
public $path;
/**
* @param string $path
*/
public function __construct($path)
{
$this->path = $path;
}
public function log($message, $priority = self::INFO)
{
$line = $this->formatLogLine($message);
if (!@file_put_contents($this->path, $line . PHP_EOL, FILE_APPEND | LOCK_EX)) { // @ is escalated to exception
throw new \RuntimeException("Unable to write to log file '{$this->path}'. Is directory writable?");
}
}
/**
* @param string|\Exception|\Throwable
* @return string
*/
protected function formatLogLine($message)
{
return implode(' ', [
@date('[Y-m-d H-i-s]'), // @ timezone may not be set
preg_replace('#\s*\r?\n\s*#', ' ', $this->formatMessage($message)),
' @ ' . Helpers::getSource(),
]);
}
/**
* @param string|\Exception|\Throwable
* @return string
*/
protected function formatMessage($message)
{
if ($message instanceof \Exception || $message instanceof \Throwable) {
while ($message) {
$tmp[] = ($message instanceof \ErrorException
? Helpers::errorTypeToString($message->getSeverity()) . ': ' . $message->getMessage()
: Helpers::getClass($message) . ': ' . $message->getMessage() . ($message->getCode() ? ' #' . $message->getCode() : '')
) . ' in ' . $message->getFile() . ':' . $message->getLine();
$message = $message->getPrevious();
}
$message = implode("\ncaused by ", $tmp);
} elseif (!is_string($message)) {
$message = Dumper::toText($message);
}
return trim($message);
}
}