Last active
May 12, 2025 12:45
-
-
Save philipjohn/03d44e99f6be76d162bf to your computer and use it in GitHub Desktop.
A useful error logging function intended for use with WordPress. Simply add to your wp-config.php, or other non-version controlled PHP file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( ! defined( 'PJID' ) ) define( 'PJID', uniqid() ); | |
if ( ! defined( 'PJLOG' ) ) define( 'PJLOG', ABSPATH . 'pj.log' ); | |
function pj_error_log(){ | |
// Get line numbers and such | |
$caller = array_shift( debug_backtrace() ); | |
$prefix = implode( '::', [ | |
PJID, | |
$caller['file'], | |
$caller['line'], | |
$caller['function'], | |
] ); | |
$msgs = []; | |
// First we check if we're being asked to print a pretty message | |
if ( func_num_args() == 2 && is_string( func_get_arg(0) ) ) { | |
$msgs[] = sprintf( | |
'%s:%s', | |
func_get_arg(0), | |
var_export( func_get_arg(1), true ) | |
); | |
} | |
// Otherwise, just print each message/var accordingly. | |
else if ( ! empty( func_get_args() ) ) { | |
foreach ( func_get_args() as $arg ) { | |
$msgs[] = ( is_string( $arg ) ) ? $arg : var_export( $arg, true ); | |
} | |
} | |
$log = fopen( PJLOG, 'a' ); | |
array_map( function($msg) use ($log, $prefix) { | |
$msg = sprintf( '%s - %s', $prefix, $msg ); | |
fwrite( $log, $msg . PHP_EOL ); | |
}, $msgs ); | |
fclose( $log ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment