Skip to content

Instantly share code, notes, and snippets.

@mishterk mishterk/Dump.php
Created Oct 19, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.