initial
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Logger;
|
||||
|
||||
class Logger {
|
||||
private const FILE = 'reservair.log';
|
||||
|
||||
public static function info(string $message): void {
|
||||
self::write($message, 'info');
|
||||
}
|
||||
|
||||
public static function warning(string $message): void {
|
||||
self::write($message, 'warning');
|
||||
}
|
||||
|
||||
/** Accepts a Throwable so it can replace error_log($e) call sites directly. */
|
||||
public static function error(string|\Throwable $message): void {
|
||||
self::write($message instanceof \Throwable ? (string) $message : $message, 'error');
|
||||
}
|
||||
|
||||
public static function get_path(): string {
|
||||
return self::dir() . '/' . self::FILE;
|
||||
}
|
||||
|
||||
/** @return array<array{time: string, level: string, message: string}> Most-recent entry first. */
|
||||
public static function get_entries(): array {
|
||||
$path = self::get_path();
|
||||
if (!file_exists($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$entries = [];
|
||||
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
|
||||
$entry = json_decode($line, true);
|
||||
if ($entry !== null) {
|
||||
$entries[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return array_reverse($entries);
|
||||
}
|
||||
|
||||
public static function clear(): void {
|
||||
$path = self::get_path();
|
||||
if (file_exists($path)) {
|
||||
file_put_contents($path, '', LOCK_EX);
|
||||
}
|
||||
}
|
||||
|
||||
private static function write(string $message, string $level): void {
|
||||
self::ensure_dir();
|
||||
$line = json_encode([
|
||||
'time' => (new \DateTime('now', wp_timezone()))->format('Y-m-d H:i:s'),
|
||||
'level' => $level,
|
||||
'message' => $message,
|
||||
]);
|
||||
file_put_contents(self::get_path(), $line . PHP_EOL, FILE_APPEND | LOCK_EX);
|
||||
}
|
||||
|
||||
private static function dir(): string {
|
||||
static $dir = null;
|
||||
if ($dir === null) {
|
||||
$dir = wp_upload_dir()['basedir'] . '/reservair';
|
||||
}
|
||||
return $dir;
|
||||
}
|
||||
|
||||
private static function ensure_dir(): void {
|
||||
$dir = self::dir();
|
||||
if (!is_dir($dir)) {
|
||||
wp_mkdir_p($dir);
|
||||
// Block direct browser access to the log file.
|
||||
file_put_contents($dir . '/.htaccess', "Deny from all\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user