Uploaded on Sep 13, 2023
loggingStructure_php_edit
logging Structure
{
"log_type": "error|info|warning|debug", // The severity of the log
"timestamp": "ISO_format_time", // Time when the log was generated.
"module": "module/plugin/theme_name", // Which part of WordPress generated the log.
"action": "specific_action_or_event", // What was being done when the log was generated.
"user": {
"id": "user_id", // ID of the logged-in user
"username": "username", // Username of the logged-in user
"role": "user_role" // Role of the user (e.g., administrator, editor, subscriber)
},
"request": {
"url": "current_url", // The URL of the page where the action occurred.
"method": "GET|POST|PUT", // HTTP method.
"ip": "user_ip_address" // IP address of the user
},
"message": "detailed_message", // A detailed description of the log/event
"data": {
// Any additional data related to the log.
// This could include post IDs, theme settings, plugin configurations, etc.
}
}
Centralized Function
function custom_log($logtype, $module, $action, $message, $user = array(), $request = array(), $data =
array() ) {
$log = array(
"log_type"=> $logtype,
"timestamp" => date('c'), // ISO format
"module" => $module,
"action" => $action,
"message" => $message,
"user" => $user,
"request" => $request,
"data" => $data
);
send_to_external_service($log);
}
Integration with External / Internal Services
function send_to_external_service( $log ) {
// For example, using elasticsearch:
send_to_elasticsearch($log);
// For example, using WordPress debug.log:
write_wp_log($log);
}
WordPress debug.log implementation
function write_wp_log( $log ) {
// Convert the structured data to a JSON string
$log_string = json_encode( $log, JSON_PRETTY_PRINT );
// Use error_log to write the stringified log data to WP's debug.log
error_log( $log_string );
}
Elasticsearch implementation
function send_to_elasticsearch( $log ) {
$es_url = 'ES IP/wordpress_logs/_doc/';
$args = array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json'),
'body' => json_encode( $log )
);
wp_remote_request( $es_url, $args );
}
Comments