在PHP中,日志记录是记录程序运行过程中的重要信息,有助于诊断问题和分析性能。然而,大量的冗余日志信息可能会导致日志文件变得庞大且难以阅读。为了减少冗余信息,可以采取以下几种策略:
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');
通过以上方法,可以有效地减少PHP日志记录中的冗余信息,使日志更加简洁和易于分析。