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
|
<?php
namespace Asko\Loggr\Drivers;
use Asko\Loggr\Driver;
use DateTime;
/**
* @author Asko Nõmm <asko@faultd.com>
*/
class FileSystemDriver implements Driver
{
public function __construct(
private readonly string $directory,
) {}
/**
* Logs a serialized message to a file. The log file is created on a daily basis.
* If the required directory or log file does not exist, they are created.
* Ensures that the log file is writable before attempting to write the message.
*
* @param string $serializedMessage The message to be logged, serialized as a string.
* @return void
* @throws \RuntimeException If the log file or directory cannot be created, or if the log file is not writable.
*/
public function log(string $serializedMessage): void
{
// If there's no parent directory, try creating one
if (!is_dir($this->directory)) {
mkdir($this->directory, 0600, true);
}
$date = new DateTime();
$file_name = "{$date->format('Y-m-d')}.log";
$path = $this->directory . DIRECTORY_SEPARATOR . $file_name;
// If the log file does not exist, try creating one
if (!$this->exists($path)) {
throw new \RuntimeException('Log file could not be created at path: ' . $path);
}
// We managed to get this far, but still can't write to the log file
if (!$this->isWriteable($path)) {
throw new \RuntimeException('Log file is not writeable at path: ' . $path);
}
$this->write($path, $serializedMessage . PHP_EOL);
}
public function exists(string $path): bool
{
return file_exists($path);
}
public function isWriteable(string $path): bool
{
return is_writeable($path);
}
public function write(string $path, string $data): void
{
file_put_contents(
filename: $path,
data: $data,
flags: FILE_APPEND
);
}
}
|