Last active
October 27, 2020 16:01
-
-
Save lumpysimon/ae433ed240009194e57d6fc1ff9fd533 to your computer and use it in GitHub Desktop.
A simple logging class
This file contains 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 | |
namespace Simon\Src\Log; | |
// How to use this class: | |
// | |
// $logging = new Logging(); | |
// $message = 'This is a message'; | |
// $thing = [ 'Hello', 27, 'What' ]; | |
// $logging->log( $message ); | |
// $logging->log( $thing ); | |
/** | |
* Custom logging class. | |
*/ | |
class Logging { | |
/** | |
* Adds a prefix to all log messages so we can easily spot them. | |
* | |
* @var string | |
*/ | |
public $prefix = 'Simon: '; | |
/** | |
* Logging is not enabled out of the box. | |
* | |
* @var boolean | |
*/ | |
public $enabled = false; | |
/** | |
* The path to the log file if we don't want to use the defualt. | |
* | |
* @var string | |
*/ | |
public $location; | |
/** | |
* Construct the class, check the constants to decide if logging is enabled and where we're logging things to. | |
*/ | |
public function __construct() { | |
if ( defined( 'SIMON_LOGGING_ENABLED' ) and \SIMON_LOGGING_ENABLED ) { | |
$this->enabled = true; | |
} | |
if ( defined( 'SIMON_LOG_PATH' ) && is_writable( \SIMON_LOG_PATH ) ) { | |
$this->location = SIMON_LOG_PATH; | |
} | |
if ( defined( 'SIMON_LOG_PREFIX' ) and \SIMON_LOG_PREFIX ) { | |
$this->prefix = SIMON_LOG_PREFIX; | |
} | |
} | |
/** | |
* Log the message to somewhere (if logging is enabled). | |
* | |
* @param string|array|object $message The thing to log. | |
* @return void | |
*/ | |
public function log( $message ) { | |
if ( ! $this->enabled ) { | |
return; | |
} | |
if ( is_array( $message ) or is_object( $message ) ) { | |
$message = print_r( $message, true ); | |
} | |
if ( empty( $this->location ) ) { | |
error_log( $this->prefix . $message ); | |
} else { | |
error_log( $this->prefix . $message, 3, $this->location ); | |
} | |
} | |
} // class Logging |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment