在PHP中,日志記錄是記錄程序運(yùn)行過(guò)程中的重要信息,有助于診斷問(wèn)題和分析性能。然而,大量的冗余日志信息可能會(huì)導(dǎo)致日志文件變得龐大且難以閱讀。為了減少冗余信息,可以采取以下幾種策略:
define('LOG_LEVEL', 'ERROR');
if ($log_level === 'DEBUG') {
error_log('This is a debug message', 3, 'debug.log');
} elseif ($log_level === 'INFO') {
error_log('This is an info message', 3, 'info.log');
} elseif ($log_level === 'WARNING') {
error_log('This is a warning message', 3, 'warning.log');
} elseif ($log_level === 'ERROR') {
error_log('This is an error message', 3, 'error.log');
}
function customLog($message) {
$logFile = 'custom.log';
$logEntry = date('Y-m-d H:i:s') . ' [' . strtoupper(substr(error_get_last_error_msg(), 0, 1)) . '] ' . $message . PHP_EOL;
file_put_contents($logFile, $logEntry, FILE_APPEND);
}
require_once 'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('my_app');
$handler = new StreamHandler('logs/my_app.log', Logger::INFO);
$logger->pushHandler($handler);
$logger->info('This is an info message');
function filterSensitiveInfo($message) {
$sensitive_patterns = [
'/password\s*=\s*[\'"]?([^\'">]+)([\'">])/',
'/api_key\s*=\s*[\'"]?([^\'">]+)([\'">])/',
];
foreach ($sensitive_patterns as $pattern) {
$message = preg_replace($pattern, '[FILTERED]', $message);
}
return $message;
}
$filtered_message = filterSensitiveInfo('User password is 123456 and API key is abcdef');
error_log($filtered_message, 3, 'filtered_log.log');
通過(guò)以上方法,可以有效地減少PHP日志記錄中的冗余信息,使日志更加簡(jiǎn)潔和易于分析。