-
Notifications
You must be signed in to change notification settings - Fork 0
/
Loggable.php
123 lines (106 loc) · 2.88 KB
/
Loggable.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
<?php
namespace PHPUnitLog;
/**
* Simple logger for PHPUnit tests.
*
* Features:
*
* - Use self::print( $message ) to print a message to console.
*
* - Use self::log( $message ) to log a message to file. The file will
* be named after the test class, and be placed in the logs subfolder.
*
* - Choose a custom subfolder for the log files via the environment variable
* 'logsPath'.
*
* - You can change the full path of the log file (including its name and
* extension) by overriding the static method getLogFilePath().
*
* - For even more control, directly plug-in an output stream by overriding
* the static method getLogStream().
*
* - To clean the log file before each run, simply delete it in the
* constructor: unlink( self::getLogFilePath() );
*/
trait Loggable
{
/**
* Print a log message to console.
*
* @param mixed $message
*/
protected static function print($message): void
{
static::log($message, STDERR);
}
/**
* Print a log message to file.
*
* @param mixed $message
* @param resource $stream optional stream to which the message will be
* written. If not specified, the stream returned by getLogStream() will
* be used.
*/
protected static function log($message, $stream = null): void
{
if (!$stream) {
$stream = static::getLogStream();
}
if (is_array($message) || is_object($message)) {
fwrite($stream, print_r($message, true));
} else {
fwrite($stream, $message);
}
fwrite($stream, PHP_EOL);
}
/**
* Path to the log file
*/
protected static function getLogFilePath(): string
{
$dir = $_ENV['logsPath'] ?? 'tests/logs';
$path =
$dir .
DIRECTORY_SEPARATOR .
(new \ReflectionClass(static::class))->getShortName() .
'.log';
return $path;
}
/**
* The log will be sent to the stream returned by
* this method
*
* @return resource
*/
protected static function getLogStream()
{
static::maybeCreateDir();
$filePath = static::getLogFilePath();
$file = fopen($filePath, 'a');
if (!$file) {
throw new \Exception("Could not open log file {$filePath}");
}
return $file;
}
/**
* Create the logs directory if it does not exist
*/
protected static function maybeCreateDir(): bool
{
$dir = dirname(static::getLogFilePath());
if (!file_exists($dir)) {
return mkdir($dir, 0744, true);
}
return true;
}
/**
* Delete log file for the class
*/
protected static function deleteLogFile(): bool
{
if (!file_exists(static::getLogFilePath())) {
return true;
}
return unlink(static::getLogFilePath());
}
}