Skip to content

fix(cli/agent): wrap lumberjack logger to prevent re-open #8229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 10 additions & 12 deletions cli/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,12 @@ func (r *RootCmd) workspaceAgent() *clibase.Cmd {
// Spawn a reaper so that we don't accumulate a ton
// of zombie processes.
if reaper.IsInitProcess() && !noReap && isLinux {
logWriter := &lumberjack.Logger{
logWriter := &lumberjackWriteCloseFixer{w: &lumberjack.Logger{
Filename: filepath.Join(logDir, "coder-agent-init.log"),
MaxSize: 5, // MB
// Without this, rotated logs will never be deleted.
MaxBackups: 1,
}
}}
defer logWriter.Close()

sinks = append(sinks, sloghuman.Sink(logWriter))
Expand Down Expand Up @@ -149,14 +149,12 @@ func (r *RootCmd) workspaceAgent() *clibase.Cmd {
// reaper.
go DumpHandler(ctx)

ljLogger := &lumberjack.Logger{
logWriter := &lumberjackWriteCloseFixer{w: &lumberjack.Logger{
Filename: filepath.Join(logDir, "coder-agent.log"),
MaxSize: 5, // MB
// Without this, rotated logs will never be deleted.
MaxBackups: 1,
}
defer ljLogger.Close()
logWriter := &closeWriter{w: ljLogger}
}}
defer logWriter.Close()

sinks = append(sinks, sloghuman.Sink(logWriter))
Expand Down Expand Up @@ -403,24 +401,24 @@ func ServeHandler(ctx context.Context, logger slog.Logger, handler http.Handler,
}
}

// closeWriter is a wrapper around an io.WriteCloser that prevents
// writes after Close. This is necessary because lumberjack will
// re-open the file on write.
type closeWriter struct {
// lumberjackWriteCloseFixer is a wrapper around an io.WriteCloser that
// prevents writes after Close. This is necessary because lumberjack
// re-opens the file on Write.
type lumberjackWriteCloseFixer struct {
w io.WriteCloser
mu sync.Mutex // Protects following.
closed bool
}

func (c *closeWriter) Close() error {
func (c *lumberjackWriteCloseFixer) Close() error {
c.mu.Lock()
defer c.mu.Unlock()

c.closed = true
return c.w.Close()
}

func (c *closeWriter) Write(p []byte) (int, error) {
func (c *lumberjackWriteCloseFixer) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()

Expand Down