Skip to content

prevent panic and resource leak in file rotation#48

Open
larspehrsson wants to merge 4 commits intomasterfrom
rolling_log_fix
Open

prevent panic and resource leak in file rotation#48
larspehrsson wants to merge 4 commits intomasterfrom
rolling_log_fix

Conversation

@larspehrsson
Copy link
Contributor

The log rotation logic could cause a panic by attempting to access a closed file handle when renaming log files.

This is resolved by:

  • Caching the filename in the roll() function before the file is closed.
  • Setting the file handle to nil after closing it.
  • Adding a nil check in CloseAllOpenFileLoggers() to handle already-rolled files.

Additionally, a resource leak is fixed where rolling files were repeatedly added to the global open files slice. A new 'registered' flag ensures each file is added only once.

As a minor improvement, the log writer now combines the timestamp and message into a single buffer to perform one atomic write preventing splitting up timestamp and message into different logs

The log rotation logic could cause a panic by attempting to access a closed file handle when renaming log files.

This is resolved by:
- Caching the filename in the roll() function before the file is closed.
- Setting the file handle to nil after closing it.
- Adding a nil check in CloseAllOpenFileLoggers() to handle already-rolled files.

Additionally, a resource leak is fixed where rolling files were repeatedly added to the global open files slice. A new 'registered' flag ensures each file is added only once.

As a minor improvement, the log writer now combines the timestamp and message into a single buffer to perform one atomic write preventing splitting up timestamp and message into different logs
Capture and return roll() error in rollingFile.Write to avoid proceeding with a write when log rotation fails
Ensures writes can resume after rotation or startup by calling open() if rf.file is nil. If open fails, return the error instead of attempting to write.
If a file rotation (`roll`) fails after closing the file but before reopening a new one, the file handle would be left as `nil`. Subsequent calls to `Write` would trigger another roll, leading to a panic when `roll` tried to access the `nil` file handle.

This change moves the `nil` file check from `Write` into `roll` to ensure the file is open before proceeding with rotation logic, thus preventing the panic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants