Skip to content

Instantly share code, notes, and snippets.

@breadthe
Created April 2, 2022 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breadthe/b8a7952bf2bbdf4f6df33ac75ec870f8 to your computer and use it in GitHub Desktop.
Save breadthe/b8a7952bf2bbdf4f6df33ac75ec870f8 to your computer and use it in GitHub Desktop.
Barebones PHP error logging class
<?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