PHP debugging can involve outputting to a log file. Although modern frameworks like Laravel has this baked in, sometimes you just want something short and sweet that will do the job. As such we present you with our ultimate PHP debugger:
function debugger( $message, $variable = '' ) {
$serverAddr = $_SERVER['SERVER_ADDR'];
$dateTimeFormat = date( 'Y-m-d H:i:s' );
$prefix = "[$dateTimeFormat] $serverAddr.PREFIX: ";
if ( is_array( $variable ) or is_object( $variable ) ) {
$variable = print_r( $variable, 1 );
} else if ( gettype( $variable ) == 'boolean' ) {
$variable = "(Boolean: $variable)";
}
file_put_contents( './log_' . date( "dmY" ) . '.log', $prefix . $message . $variable . "\n", FILE_APPEND );
}
Sample Usage
debugger("This is a test"); debugger("This is an array", [1,2,3]); debugger("This application exists $counter times in Gravity Forms");
Anatomy of the Ultimate Debugger
This debugger works with or without a variable. In the case of a variable sent with it, it can interpret three kinds:
- Arrays
- Objects
- Booleans
When the debugger encounters a boolean, the boolean is outputted in brackets to accommodate where it’s false.
In the above example PREFIX
can be anything, and one could also include it as a variable if so desired.
This debugger should be defined the the root of your application, or any any fixed location so that you can find the log file. One example would be if you’re using it with WordPress, you want to define it in wp-config.php
Once you have the debugger working, tail the output like so:
➜ ~ tail -f code/myapp/log_01092020.log [2020-09-01 08:02:17] 127.0.0.1.FINTECH: BackOffice API reports this duplicate expires in (Boolean: ) [2020-09-01 08:02:18] 127.0.0.1.FINTECH: BackOffice API response in gform_after_submission: {"status":"success","message":"Application is a duplicate, expires in 37 seconds, not dispatching","data":{"expired":false,"timeout":83,"remainder":37,"wait_time":120,"no_wordpress_redirect":false}} [2020-09-01 08:16:30] 127.0.0.1.FINTECH: Gravity Forms is verifying the the ID number: 123 [2020-09-01 08:16:32] 127.0.0.1.FINTECH: Gravity Forms custom_confirmation checking duplicate count... [2020-09-01 08:16:32] 127.0.0.1.FINTECH: BackOffice API expiryEndpoint: https://super-duper-app.test/api/v1/application/expiry/123?api_token=secret
References
- https://stackoverflow.com/questions/19898688/how-to-create-a-logfile-in-php
- Ideas borrowed from Laravel’s logger, https://laravel.com/docs/logging