Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to use a Static method or Object for a Logger in PHP?

Tags:

php

I have a very simple Logger class below, my goal is to make log function calls and write the data to a log file but to only make 1 write per page no matter how many times I call the log function

session_start();
class JD{
    static private $log = array();

    public function __construct(){  }

    // Simple logger
    // usage JD::log('debug', 'MySQLi Database Driver Initialized');
    public static function log($mode, $message){
        self::$log[] = '[' .$mode. '] = ' .$message. '\r\n';
        $_SESSION['jdlog'] = self::$log;

    }
}

testing

JD::log('debug', 'MySQLi Database Driver Initialized');
JD::log('debug2', 'MySQLi Database Driver Initialized');
JD::log('debug3', 'MySQLi Database Driver Initialized');
JD::log('debug4', 'MySQLi Database Driver Initialized');
JD::log('debug5', 'MySQLi Database Driver Initialized');
JD::log('debug6', 'MySQLi Database Driver Initialized');
print_r($_SESSION['jdlog']);

Ok based on that simple code above, it would appear that it is probably better to just use the static method like I did but I am wanting to write the array of log messages to a file or somewhere else, so with my current method above, it would have to write to a file on every single function call, which defeats the purpose of me saving each call into an array.

If I make it a regular class object then I can simply instantiate my object, make my log function calls as needed, then make 1 write at the end of my page by calling another function that will write the array to file, I can also do away with saving to session.

How would you do something simple like this?

like image 644
JasonDavis Avatar asked Nov 19 '25 17:11

JasonDavis


1 Answers

You can write a destructor method to handle the file writing when the script execution ends.

like image 197
Narf Avatar answered Nov 22 '25 08:11

Narf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!