WordPress có chức năng ghi nhật ký được tích hợp sẵn và dễ dàng thêm vào, nhưng nếu bạn muốn tạo tệp nhật ký tùy chỉnh WordPress của riêng mình cho một plugin hoặc chủ đề thì sao?
Theo dõi các vấn đề hoặc lưu trữ thông tin không nhạy cảm là một điều khó khăn với nhật ký tùy chỉnh WordPress. Dễ dàng thêm các câu lệnh gỡ lỗi để giúp khắc phục lỗi hoặc ghi lại thông tin hữu ích bằng cách sử dụng hàm fopenvà fwrite.
if ( ! function_exists( 'plugin_log' ) ) {
function plugin_log( $entry, $mode = 'a', $file = 'plugin' ) {
// Get WordPress uploads directory.
$upload_dir = wp_upload_dir();
$upload_dir = $upload_dir['basedir'];
// If the entry is array, json_encode.
if ( is_array( $entry ) ) {
$entry = json_encode( $entry );
}
// Write the log file.
$file = $upload_dir . '/' . $file . '.log';
$file = fopen( $file, $mode );
$bytes = fwrite( $file, current_time( 'mysql' ) . "::" . $entry . "\n" );
fclose( $file );
return $bytes;
}
}
Usage:
// Append an entry to the uploads/plugin.log file.
plugin_log( 'Something happened.' );
// Append an array entry to the uploads/plugin.log file.
plugin_log( ['new_user' => 'nguyenlap' ] );
// Write an entry to the uploads/plugin.log file, deleting the existing entries.
plugin_log( 'Awesome sauce.', 'w' );
// Append an entry to a different log file in the uploads directory.
plugin_log( 'Simple stuff.', 'a', 'simple-stuff' );
