WordPress developers often spend significant time debugging code, especially when dealing with silent errors or POST requests that don’t yield any frontend response. Instead of storing Data in the database, which is inefficient, using Wonolog, a tool that integrates the popular php logging library Monolog into WordPress, can greatly simplify error tracking and debugging.
With Wonolog, all PHP and database errors, warnings, and notifications can be captured. By leveraging Monolog’s error handlers, we can write these errors to log files or even send them via emAIl to site administrators. To incorporate Wonolog into your project managed by Composer, add the following line to your `composer.json`:
“`json
require: {
“inpsyde/wonolog”: “^版本号”
}
“`
Then, initialize Wonolog with:
“`php
\Inpsyde\Wonolog\Bootstrap();
“`
The `WP_DEBUG_LOG` constant controls what gets logged. If set to `true`, Wonolog logs all warnings, errors, and debug info. If set to `false`, it only logs errors.
To manually log information during development, use the `wonolog.log` Action:
“`php
do_action(‘wonolog.log’, [
‘message’ => ‘Something happened.’,
‘channel’ => ‘debug’,
‘level’ => \Monolog\Logger::DEBUG,
‘context’ => [],
]);
“`
By default, logs are saved in `wp-content/wonolog/{y/m/d}.log`. Open these files to view the log entries.
For severe errors, you can configure Wonolog to send email notifications to site administrators. Monolog offers a NativeMailerHandler for this purpose. Extend it for better compatibility with WordPress’ `wp_mail()` function:
“`php
namespace Example;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\NativeMailerHandler;
class WPMailHandler extends NativeMailerHandler {
protected function send(string $content, array $records) {
//… same as before, but use wp_mail() instead of mail()
}
}
$email_handler = new WPMailHandler(‘you@example.com’, ‘Error on ‘ . home_url(), ‘logs@example.com’, \Monolog\Logger::ERROR);
\Inpsyde\Wonolog\bootstrap()->use_handler($email_handler);
“`
AdDiTionally, you can utilize other Monolog handlers to send error messages to services like Slack or Papertrail.
Detailed logging empowers developers to easily track and diagnose issues during WordPress application development. It’s not just about error logging; for financially-oriented Websites, transaction details can also be logged to facilitate auditing in case of discrepancies. The clearer the logs, the more confidence you’ll have in your application’s stability.