Here’s a nice little PHP helper function I’ve been using for the past few years for debugging my code:
if ( !function_exists( 'log_this' ) ){
function log_this( $title, $data = false ){
if ( func_num_args( ) === 0 ){
return false;
}
elseif ( func_num_args( ) === 1 ){
$data = $title;
$title = "LOG";
}
$border_char = "/";
$border_length_bottom = 100;
$border_length_top = $border_length_bottom - strlen( $title ) - 2;
$border_length_top_left = floor( $border_length_top/2 );
$border_length_top_right = ceil( $border_length_top/2 );
$border_top_left = str_pad( "", $border_length_top_left, $border_char );
$border_top_right = str_pad( "", $border_length_top_right, $border_char );
error_log( "\n\n" );
error_log( "$border_top_left $title $border_top_right" );
if ( is_array( $data ) || is_object( $data ) ){
error_log( print_r( $data, true ) );
}
else{
error_log( "" );
error_log( $data );
error_log( "" );
}
error_log( str_pad( "", $border_length_bottom, $border_char ) . "\n" );
}
}
As you can see, this is mostly a wrapper around the built-in error_log
PHP function with the advantage of letting you log arrays without needing to use print_r
. And it makes the variables you’re logging easier to see in a crowded log file.
Here’s an example use.
$hello = 'world';
log_this( $hello );
/////////////////////////////////////////////// LOG ////////////////////////////////////////////////
world
////////////////////////////////////////////////////////////////////////////////////////////////////
And now with an array.
$user = array(
'name' => 'Stefan',
'location' => 'Brooklyn, New York',
'number_of_pets' => 1
);
log_this( $user );
/////////////////////////////////////////////// LOG ////////////////////////////////////////////////
Array
(
[name] => Stefan
[location] => Brooklyn, New York
[number_of_pets] => 1
)
////////////////////////////////////////////////////////////////////////////////////////////////////
And here’s a more complex example that also shows how you can modify the text before your variable, making it easier to find it by searching that text.
$hello = 'world';
$my_number = 12345;
$user = array(
'name' => 'Stefan',
'location' => 'Brooklyn, New York',
'number_of_pets' => 1
);
log_this( 'debugging:user data', array(
'$hello' => $hello,
'$my_number' => $my_number,
'$user' => $user,
) );
/////////////////////////////////////// debugging:user data ////////////////////////////////////////
Array
(
[$hello] => world
[$my_number] => 12345
[$user] => Array
(
[name] => Stefan
[location] => Brooklyn, New York
[number_of_pets] => 1
)
)
////////////////////////////////////////////////////////////////////////////////////////////////////