Skip to content

Commit

Permalink
Optimise memory usage when formatting logger entries (#10216)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmvrtx authored Jan 22, 2025
1 parent cce23de commit d8036a3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 21 deletions.
4 changes: 4 additions & 0 deletions changelog/dev-10021-logging-memory-optimisations
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: dev

Optimise memory consumption when formatting log entries.
36 changes: 15 additions & 21 deletions src/Internal/LoggerContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ public function filter_log_entry( $entry, $context ): string {
return $entry;
}

$entry_number = ++$this->entry_number;
$time_string = gmdate( 'c', $context['timestamp'] );
$level_string = strtoupper( $context['level'] );
$format_string = sprintf( '%s %s %s-%04d %%s', $time_string, $level_string, $this->request_id, $entry_number );
$entry_number = ++$this->entry_number;
$time_string = gmdate( 'c', $context['timestamp'] );
$level_string = strtoupper( $context['level'] );
$line_prefix = sprintf( '%s %s %s-%04d ', $time_string, $level_string, $this->request_id, $entry_number );

$entries = [ $context['message'] ];

Expand All @@ -124,23 +124,17 @@ public function filter_log_entry( $entry, $context ): string {
$this->context_updated = false;
}

return implode(
"\n",
array_map(
function ( $entry ) use ( $format_string ) {
return implode(
"\n",
array_map(
function ( $line ) use ( $format_string ) {
return sprintf( $format_string, $line );
},
explode( "\n", $entry )
)
);
},
$entries
)
);
$formatted_lines = [];
$log_entry = array_shift( $entries );
while ( null !== $log_entry ) {
foreach ( explode( "\n", $log_entry ) as $line ) {
$formatted_lines[] = $line_prefix . $line;
}
unset( $log_entry );
$log_entry = array_shift( $entries );
}

return implode( "\n", $formatted_lines );
}

/**
Expand Down

0 comments on commit d8036a3

Please sign in to comment.