| @@ -36,21 +36,59 @@ | ||
| 36 | 36 | * @param mixed $message Message to log |
| 37 | 37 | * @return void |
| 38 | 38 | */ |
| 39 | 39 | private function log( string $log_level, $message ): void { |
| 40 | - $backtrace = debug_backtrace(); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace | |
| 40 | + $raw_message = $this->message_to_string( $message ); | |
| 41 | + $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace | |
| 41 | 42 | |
| 43 | + $caller = $this->caller_from_backtrace( $backtrace ); | |
| 44 | + | |
| 45 | + $formatted_message = '[' . $this->prefix . ']: ' . $log_level . ' in ' . $caller . ': ' . $raw_message; | |
| 46 | + | |
| 47 | + error_log( $formatted_message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log | |
| 48 | + | |
| 49 | + LogStore::instance()->append( | |
| 50 | + $log_level, | |
| 51 | + $raw_message, | |
| 52 | + [ | |
| 53 | + 'source' => $this->prefix, | |
| 54 | + 'call_stack' => $caller, | |
| 55 | + ] | |
| 56 | + ); | |
| 57 | + } | |
| 58 | + | |
| 59 | + /** | |
| 60 | + * @param mixed $message | |
| 61 | + * @return string | |
| 62 | + */ | |
| 63 | + private function message_to_string( $message ): string { | |
| 64 | + if ( is_string( $message ) ) { | |
| 65 | + return $message; | |
| 66 | + } | |
| 67 | + | |
| 68 | + if ( is_scalar( $message ) ) { | |
| 69 | + return (string) $message; | |
| 70 | + } | |
| 71 | + | |
| 72 | + $encoded = wp_json_encode( $message ); | |
| 73 | + | |
| 74 | + return is_string( $encoded ) ? $encoded : ''; | |
| 75 | + } | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * @param array<int, array<string, mixed>> $backtrace | |
| 79 | + * @return string | |
| 80 | + */ | |
| 81 | + private function caller_from_backtrace( array $backtrace ): string { | |
| 42 | 82 | $class = $backtrace[2]['class'] ?? null; |
| 43 | 83 | $type = $backtrace[2]['type'] ?? null; |
| 44 | - $function = $backtrace[2]['function']; | |
| 84 | + $function = $backtrace[2]['function'] ?? ''; | |
| 45 | 85 | |
| 46 | 86 | if ( $class ) { |
| 47 | - $message = '[' . $this->prefix . ']: ' . $log_level . ' in ' . "$class$type$function()" . ': ' . $message; | |
| 48 | - } else { | |
| 49 | - $message = '[' . $this->prefix . ']: ' . $log_level . ' in ' . "$function()" . ': ' . $message; | |
| 87 | + return "$class$type$function()"; | |
| 50 | 88 | } |
| 51 | 89 | |
| 52 | - error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log | |
| 90 | + return "$function()"; | |
| 53 | 91 | } |
| 54 | 92 | |
| 55 | 93 | /** |
| 56 | 94 | * Log an error message |