Skip to content
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

promslog: Only log basename, not full path #705

Merged
merged 1 commit into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
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
16 changes: 14 additions & 2 deletions promslog/slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,17 @@ var (
default:
}

return a
}
truncateSourceAttrFunc = func(groups []string, a slog.Attr) slog.Attr {
if a.Key != slog.SourceKey {
return a
}

if src, ok := a.Value.Any().(*slog.Source); ok {
a.Value = slog.StringValue(filepath.Base(src.File) + ":" + strconv.Itoa(src.Line))
}

return a
}
)
Expand Down Expand Up @@ -165,8 +176,9 @@ func New(config *Config) *slog.Logger {
}

logHandlerOpts := &slog.HandlerOptions{
Level: config.Level.lvl,
AddSource: true,
Level: config.Level.lvl,
AddSource: true,
ReplaceAttr: truncateSourceAttrFunc,
}

if config.Style == GoKitStyle {
Expand Down
44 changes: 44 additions & 0 deletions promslog/slog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,47 @@ func TestDynamicLevels(t *testing.T) {
})
}
}

func TestTruncateSourceFileName_DefaultStyle(t *testing.T) {
var buf bytes.Buffer

config := &Config{
Writer: &buf,
}

logger := New(config)
logger.Info("test message")

output := buf.String()

if !strings.Contains(output, "source=slog_test.go:") {
t.Errorf("Expected source file name to be truncated to basename, got: %s", output)
}

if strings.Contains(output, "/") {
t.Errorf("Expected no directory separators in source file name, got: %s", output)
}
}

func TestTruncateSourceFileName_GoKitStyle(t *testing.T) {
var buf bytes.Buffer

config := &Config{
Writer: &buf,
Style: GoKitStyle,
}

logger := New(config)
logger.Info("test message")

output := buf.String()

// In GoKitStyle, the source key is "caller".
if !strings.Contains(output, "caller=slog_test.go:") {
t.Errorf("Expected caller to contain basename of source file, got: %s", output)
}

if strings.Contains(output, "/") {
t.Errorf("Expected no directory separators in caller, got: %s", output)
}
}