JasonDavis
JasonDavis

Reputation: 48933

Better to use a Static method or Object for a Logger in 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?

Upvotes: 3

Views: 152

Answers (2)

Mike Purcell
Mike Purcell

Reputation: 19979

I definitely would not trust session functionality to house log data as it is volatile in nature, especially if your are logging critical messages. You may want to look at the Zend_Log code for ideas.

To be honest, I don't think it would be a good idea to store many and write once, in case a script is abruptly halted and the write never occurs.

Upvotes: 0

Narf
Narf

Reputation: 14752

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

Upvotes: 1

Related Questions