| 1 |
<?php |
| 2 |
|
| 3 |
namespace Cookiez\Classes; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
class Logger { |
| 10 |
public const LEVEL_ERROR = 'error'; |
| 11 |
public const LEVEL_WARN = 'warn'; |
| 12 |
public const LEVEL_INFO = 'info'; |
| 13 |
public const LEVEL_DEBUG = 'debug'; |
| 14 |
|
| 15 |
public const LOG_LEVEL_PRIORITY = [ |
| 16 |
'debug' => 1, |
| 17 |
'info' => 2, |
| 18 |
'warn' => 3, |
| 19 |
'error' => 4, |
| 20 |
]; |
| 21 |
|
| 22 |
/** |
| 23 |
* @param string $log_level |
| 24 |
* @param $message |
| 25 |
* |
| 26 |
* @return void |
| 27 |
*/ |
| 28 |
private static function log( string $log_level, $message ): void { |
| 29 |
if ( |
| 30 |
defined( 'COOKIEZ_MINIMUM_LOG_LEVEL' ) && |
| 31 |
self::LOG_LEVEL_PRIORITY[ $log_level ] < (int) COOKIEZ_MINIMUM_LOG_LEVEL |
| 32 |
) { |
| 33 |
return; |
| 34 |
} |
| 35 |
|
| 36 |
$backtrace = debug_backtrace(); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace |
| 37 |
|
| 38 |
$class = $backtrace[2]['class'] ?? null; |
| 39 |
$type = $backtrace[2]['type'] ?? null; |
| 40 |
$function = $backtrace[2]['function']; |
| 41 |
|
| 42 |
if ( $class ) { |
| 43 |
$message = '[Cookiez]: ' . $log_level . ' in ' . "$class$type$function()" . ': ' . $message; |
| 44 |
} else { |
| 45 |
$message = '[Cookiez]: ' . $log_level . ' in ' . "$function()" . ': ' . $message; |
| 46 |
} |
| 47 |
|
| 48 |
error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log |
| 49 |
} |
| 50 |
|
| 51 |
public static function debug( $message ): void { |
| 52 |
self::log( self::LEVEL_DEBUG, $message ); |
| 53 |
} |
| 54 |
|
| 55 |
public static function info( $message ): void { |
| 56 |
self::log( self::LEVEL_INFO, $message ); |
| 57 |
} |
| 58 |
|
| 59 |
public static function warn( $message ): void { |
| 60 |
self::log( self::LEVEL_WARN, $message ); |
| 61 |
} |
| 62 |
|
| 63 |
public static function error( $message ): void { |
| 64 |
self::log( self::LEVEL_ERROR, $message ); |
| 65 |
} |
| 66 |
} |
| 67 |
|