feat(cli): rotate file logs for coderd (#15438)

Related to #15309 

As we already are doing for agent logs - this PR is enabling the logs
rotation for coderd logs.

Currently keeping the same logic than we had for agent - with 5MB as the
file size for rotation.
This commit is contained in:
Vincent Vielle
2024-11-12 21:48:32 +01:00
committed by GitHub
parent 56e219b50d
commit d6442db25a
2 changed files with 8 additions and 32 deletions
+8 -7
View File
@@ -4,11 +4,11 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"os"
"regexp" "regexp"
"strings" "strings"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"gopkg.in/natefinch/lumberjack.v2"
"cdr.dev/slog" "cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman" "cdr.dev/slog/sloggers/sloghuman"
@@ -104,7 +104,6 @@ func (b *Builder) Build(inv *serpent.Invocation) (log slog.Logger, closeLog func
addSinkIfProvided := func(sinkFn func(io.Writer) slog.Sink, loc string) error { addSinkIfProvided := func(sinkFn func(io.Writer) slog.Sink, loc string) error {
switch loc { switch loc {
case "": case "":
case "/dev/stdout": case "/dev/stdout":
sinks = append(sinks, sinkFn(inv.Stdout)) sinks = append(sinks, sinkFn(inv.Stdout))
@@ -112,12 +111,14 @@ func (b *Builder) Build(inv *serpent.Invocation) (log slog.Logger, closeLog func
sinks = append(sinks, sinkFn(inv.Stderr)) sinks = append(sinks, sinkFn(inv.Stderr))
default: default:
fi, err := os.OpenFile(loc, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) logWriter := &lumberjack.Logger{
if err != nil { Filename: loc,
return xerrors.Errorf("open log file %q: %w", loc, err) MaxSize: 5, // MB
// Without this, rotated logs will never be deleted.
MaxBackups: 1,
} }
closers = append(closers, fi.Close) closers = append(closers, logWriter.Close)
sinks = append(sinks, sinkFn(fi)) sinks = append(sinks, sinkFn(logWriter))
} }
return nil return nil
} }
-25
View File
@@ -2,7 +2,6 @@ package clilog_test
import ( import (
"encoding/json" "encoding/json"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -145,30 +144,6 @@ func TestBuilder(t *testing.T) {
assertLogsJSON(t, tempJSON, info, infoLog, warn, warnLog) assertLogsJSON(t, tempJSON, info, infoLog, warn, warnLog)
}) })
}) })
t.Run("NotFound", func(t *testing.T) {
t.Parallel()
tempFile := filepath.Join(t.TempDir(), "doesnotexist", "test.log")
cmd := &serpent.Command{
Use: "test",
Handler: func(inv *serpent.Invocation) error {
logger, closeLog, err := clilog.New(
clilog.WithFilter("foo", "baz"),
clilog.WithHuman(tempFile),
clilog.WithVerbose(),
).Build(inv)
if err != nil {
return err
}
defer closeLog()
logger.Error(inv.Context(), "you will never see this")
return nil
},
}
err := cmd.Invoke().Run()
require.ErrorIs(t, err, fs.ErrNotExist)
})
} }
var ( var (