Last active
June 25, 2026 13:28
-
-
Save danielecr/dd76b350d9c67dfbdaa01a540a12f4b2 to your computer and use it in GitHub Desktop.
Logger.php
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 | |
| // Logger class | |
| // see https://medium.com/@WC_/the-ultimate-guide-to-building-a-robust-logging-system-in-php-from-concept-to-deployment-05d46ac5800e | |
| class Logger | |
| { | |
| const INFO = 1; | |
| const WARNING = 2; | |
| const ERROR = 3; | |
| private static $logFilePath; | |
| public static function init($logFilePath) | |
| { | |
| self::$logFilePath = $logFilePath; | |
| } | |
| public static function log($message, $severity) | |
| { | |
| $timestamp = date('Y-m-d H:i:s'); | |
| //$timestamp = date('Y-m-d H:i:s.u'); // Includes microseconds | |
| /* | |
| switch ($severity) { | |
| case self::DEBUG: | |
| // Handle debug messages | |
| break; | |
| case self::INFO: | |
| // Handle info messages | |
| break; | |
| // ... handle other severity levels ... | |
| } | |
| */ | |
| $logMessage = "[$timestamp] [$severity] $message\n"; | |
| $fileHandle = fopen(self::$logFilePath, 'a'); | |
| fwrite($fileHandle, $logMessage); | |
| fclose($fileHandle); | |
| } | |
| public static function info($message) | |
| { | |
| if(is_array($message)){ | |
| $message = "is array: ".print_r($message,true); | |
| } | |
| self::log($message, self::INFO); | |
| } | |
| public static function warning($message) | |
| { | |
| if(is_array($message)){ | |
| $message = "is array: ".print_r($message,true); | |
| } | |
| self::log($message, self::WARNING); | |
| } | |
| public static function error($message) | |
| { | |
| if(is_array($message)){ | |
| $message = "is array: ".print_r($message,true); | |
| } | |
| self::log($message, self::ERROR); | |
| } | |
| public static function logException(Exception $e) | |
| { | |
| $message = "Exception: " . $e->getMessage() . "\nStack Trace:\n" . $e->getTraceAsString(); | |
| self::log($message, self::ERROR); | |
| } | |
| } | |
| /* | |
| usage: | |
| // Initialize the logger | |
| Logger::init('application.log'); | |
| // Log some messages | |
| Logger::info('Application started'); | |
| Logger::warning('Database connection failed'); | |
| Logger::error('Critical error: Out of memory'); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment