Skip to content

Commit 98576c3

Browse files
Merge pull request #57897 from nextcloud/backport/57590/stable33
[stable33] fix: log memory usage for requests based on configured memory limit
2 parents 7b3c071 + aa8027a commit 98576c3

1 file changed

Lines changed: 38 additions & 8 deletions

File tree

lib/base.php

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -915,16 +915,46 @@ public static function init(): void {
915915
$eventLogger->end('request');
916916
});
917917

918-
register_shutdown_function(function () {
918+
register_shutdown_function(function () use ($config) {
919919
$memoryPeak = memory_get_peak_usage();
920-
$logLevel = match (true) {
921-
$memoryPeak > 500_000_000 => ILogger::FATAL,
922-
$memoryPeak > 400_000_000 => ILogger::ERROR,
923-
$memoryPeak > 300_000_000 => ILogger::WARN,
924-
default => null,
925-
};
926-
if ($logLevel !== null) {
920+
$debugModeEnabled = $config->getSystemValueBool('debug', false);
921+
$memoryLimit = null;
922+
923+
if (!$debugModeEnabled) {
924+
// Use the memory helper to get the real memory limit in bytes if debug mode is disabled
925+
try {
926+
$memoryInfo = new \OC\MemoryInfo();
927+
$memoryLimit = $memoryInfo->getMemoryLimit();
928+
} catch (Throwable $e) {
929+
// Ignore any errors and fall back to hardcoded thresholds
930+
}
931+
}
932+
933+
// Check if a memory limit is configured and can be retrieved and determine log level if debug mode is disabled
934+
if (!$debugModeEnabled && $memoryLimit !== null && $memoryLimit !== -1) {
935+
$logLevel = match (true) {
936+
$memoryPeak > $memoryLimit * 0.9 => ILogger::FATAL,
937+
$memoryPeak > $memoryLimit * 0.75 => ILogger::ERROR,
938+
$memoryPeak > $memoryLimit * 0.5 => ILogger::WARN,
939+
default => null,
940+
};
941+
942+
$memoryLimitIni = @ini_get('memory_limit');
943+
$message = 'Request used ' . Util::humanFileSize($memoryPeak) . ' of memory. Memory limit: ' . ($memoryLimitIni ?: 'unknown');
944+
} else {
945+
// Fall back to hardcoded thresholds if memory_limit cannot be determined or if debug mode is enabled
946+
$logLevel = match (true) {
947+
$memoryPeak > 500_000_000 => ILogger::FATAL,
948+
$memoryPeak > 400_000_000 => ILogger::ERROR,
949+
$memoryPeak > 300_000_000 => ILogger::WARN,
950+
default => null,
951+
};
952+
927953
$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
954+
}
955+
956+
// Log the message
957+
if ($logLevel !== null) {
928958
$logger = Server::get(LoggerInterface::class);
929959
$logger->log($logLevel, $message, ['app' => 'core']);
930960
}

0 commit comments

Comments
 (0)