Skip to content

Instantly share code, notes, and snippets.

@ruionwriting
Last active December 20, 2015 13:29
Show Gist options
  • Save ruionwriting/6139451 to your computer and use it in GitHub Desktop.
Save ruionwriting/6139451 to your computer and use it in GitHub Desktop.
Easy to use logging class for PHP taken from Chris Valleriani blog article.
<?php
/**
* +90% based on the article of Chris Valleriani
* http://chrisvall.com/coding/php-easy-to-use-logging-class-for-your-scripts
*
* My changes:
*
* - force default timezone;
* - defines a base dir for log files output
* (sometimes I need to exec PHP through terminal, avoids "lost" log files);
* - log files name format changed to Ymd_LogName;
* - date format written to log file changed to H:i:s.
*/
date_default_timezone_set('Europe/Lisbon');
class Logger {
private $lName = null;
private $handle = null;
const BASE_DIR = '/your/logs/path/';
public function __construct($logName = null) {
if ($logName) $this->lName = $logName; //Define Log Name!
else $this->lName = "Log"; //Default name
$this->logOpen(); //Begin logging.
}
function __destruct() {
fclose($this->handle); //Close when php script ends (always better to be proper.)
}
//Open Logfile
private function logOpen(){
$fileName = self::BASE_DIR . date('Ymd') . '_' . $this->lName;
$this->handle = fopen($fileName, 'a') or exit("Can't open " . $fileName); //Open log file for writing, if it does not exist, create it.*/
}
//Write Message to Logfile
public function logWrite($message){
$time = date('H:i:s -'); //Grab Time
fwrite($this->handle, $time . " " . $message . "\n"); //Output to logfile
}
//Clear Logfile
public function logClear(){
ftruncate($this->handle, 0);
}
}

Overview

I needed a very simple and easy to use logging class for some PHP scripts I develop/maintain. I found a very straight forward approach on Chris Valleriani blog (here: http://chrisvall.com/coding/php-easy-to-use-logging-class-for-your-scripts). PHP_logging_basics.md

Setup

Just add Logger.php to your project.

Usage

<?php

require('Logger.php');

/* ... */

// init
$log = new Logger('YourLogName');

// add log entry
$log->logWrite('Starting...');

Other minor improvements

  • Move base dir to constructor args;
  • Create archiving option to compress log files and move them to folder structure like year/month/day/files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment