Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: logger update #1807

Merged
merged 3 commits into from
Jul 29, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions includes/class-logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,31 @@ class Logger {
/**
* A logger.
*
* @param any $payload The payload to log.
* @param any $payload The payload to log.
* @param string $header Log message header.
*/
public static function log( $payload ) {
if ( defined( 'NEWSPACK_LOG_LEVEL' ) && 0 < (int) NEWSPACK_LOG_LEVEL ) {
$caller = null;
public static function log( $payload, $header = 'NEWSPACK' ) {
if ( ! defined( 'NEWSPACK_LOG_LEVEL' ) || 0 > (int) NEWSPACK_LOG_LEVEL ) {
return;
}
$caller = null;

// Add information about the caller function, if log level is > 1.
if ( 1 < NEWSPACK_LOG_LEVEL ) {
try {
$backtrace = debug_backtrace(); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
if ( 2 < count( $backtrace ) ) {
$caller_frame = $backtrace[1];
$caller = $caller_frame['class'] . $caller_frame['type'] . $caller_frame['function'];
}
} catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
// Fail silently.
// Add information about the caller function, if log level is > 1.
if ( 1 < NEWSPACK_LOG_LEVEL ) {
try {
$backtrace = debug_backtrace(); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
if ( 2 < count( $backtrace ) ) {
$caller_frame = $backtrace[1];
$caller = $caller_frame['class'] . $caller_frame['type'] . $caller_frame['function'];
}
} catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
// Fail silently.
}
}

$message = 'string' === gettype( $payload ) ? $payload : wp_json_encode( $payload, JSON_PRETTY_PRINT );
$caller_prefix = $caller ? "[$caller]" : '';
$message = 'string' === gettype( $payload ) ? $payload : wp_json_encode( $payload, JSON_PRETTY_PRINT );
$caller_prefix = $caller ? "[$caller]" : '';

error_log( '[NEWSPACK]' . $caller_prefix . ': ' . $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
}
error_log( '[' . $header . ']' . $caller_prefix . ': ' . $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
}
}