Skip to content

Instantly share code, notes, and snippets.

@mishterk
Created October 19, 2019 10:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/c7cbc2d58b075e760588e28a66253779 to your computer and use it in GitHub Desktop.
Save mishterk/c7cbc2d58b075e760588e28a66253779 to your computer and use it in GitHub Desktop.
A simple static class for dumping information to a log file of your choosing. For more info, see https://philkurth.com.au/tips/a-php-class-for-dumping-data-to-a-separate-log-file/
<?php
/**
* Class Dump
* A simple static class for dumping data to a separate log file to aid debugging and development.
*
* @author Phil Kurth <phil@philkurth.com.au>
*/
class Dump {
public static $logfile;
/**
* Logs data to log file
*
* @param mixed $data
* @param string $mode Specifies write mode ('a' for append || 'w' for write)
* @param boolean $pretty If true, var_export is used
* @param boolean $informative If true, informative header is printed
*
* @throws \Exception
*/
static function log( $data, $informative = false, $mode = 'a', $pretty = true ) {
if ( ! self::$logfile ) {
throw new \Exception( 'Debug::$logfile is not set' );
}
$file_location = self::$logfile;
$datetime = new DateTime; // current time = server time
$otherTZ = new DateTimeZone( 'Australia/Melbourne' );
$datetime->setTimezone( $otherTZ ); // calculates with new TZ now
$bt = debug_backtrace();
$file = "Calling file: " . basename( $bt[0]['file'] );
$line = "Line: " . $bt[0]['line'];
$info = '';
if ( $informative ) {
$info = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n";
$info .= $datetime->format( 'm/d/Y h:i:s a' ) . "\n";
$info .= $file . "\n";
$info .= $line . "\n";
$info .= ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n";
}
// Better boolean logging
if ( $data === false ) {
$data = '(bool)FALSE';
} elseif ( $data === true ) {
$data = '(bool)TRUE';
}
if ( $pretty ) {
$info .= print_r( $data, true );
} else {
$info .= var_export( $data, true );
}
$info .= $informative ? "\n\n" : "\n";
$file = fopen( $file_location,
$mode ) or print( '<div style="background-color:#db514d;color:white;text-align:center;padding:10px;">Cannot open log file for logging</div>' );
fwrite( $file, $info );
fclose( $file );
}
}
<?php
// Include and configure the class. I usually do this in my wp-config.php
// file but you could do this in a theme or a plugin instead.
require 'class-dump.php';
Dump::$logfile = __DIR__ . '/dev.log';
// Need to dump something to the log while you are working? Easy!
Dump::log('some data');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment