Created
April 2, 2022 21:56
-
-
Save breadthe/b8a7952bf2bbdf4f6df33ac75ec870f8 to your computer and use it in GitHub Desktop.
Barebones PHP error logging class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// src/Log.php | |
namespace App; | |
/** | |
* Barebones error logging class | |
* | |
* Location: <project root>/src/Log.php | |
* | |
* Usage: | |
* App\Log::error('Your error message'); | |
* | |
* Output (<project root>/storage/logs/error.log): | |
* [2022-04-02 16:20:46] Your error message | |
*/ | |
class Log | |
{ | |
private const PATH = __DIR__ . '/../storage/logs'; | |
private const FILENAME = 'error.log'; | |
private static self|null $singleton = null; | |
protected function __construct() | |
{ | |
self::createStorageFolderIfNotExists(); | |
} | |
public static function singleton(): ?Log | |
{ | |
if (self::$singleton === null) { | |
self::$singleton = new self; | |
} | |
return self::$singleton; | |
} | |
public static function error(string $message): void | |
{ | |
(new self)->writeError($message); | |
} | |
private static function createStorageFolderIfNotExists(): void | |
{ | |
if (!file_exists(self::PATH)) { | |
mkdir(self::PATH, 0755, true); | |
} | |
} | |
private function writeError(string $message): void | |
{ | |
$line = '['. self::timestamp() . '] ' . $message; | |
$filename = self::PATH . DIRECTORY_SEPARATOR . self::FILENAME; | |
file_put_contents($filename, $line, FILE_APPEND); | |
} | |
private static function timestamp(): string | |
{ | |
return date('Y-m-d H:i:s'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment