Skip to content

Commit a9d2e3f

Browse files
authored
Merge pull request #705 from roidelapluie/sourcefile
promslog: Only log basename, not full path
2 parents dae848d + fdc50c7 commit a9d2e3f

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

promslog/slog.go

+14-2
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,17 @@ var (
6666
default:
6767
}
6868

69+
return a
70+
}
71+
truncateSourceAttrFunc = func(groups []string, a slog.Attr) slog.Attr {
72+
if a.Key != slog.SourceKey {
73+
return a
74+
}
75+
76+
if src, ok := a.Value.Any().(*slog.Source); ok {
77+
a.Value = slog.StringValue(filepath.Base(src.File) + ":" + strconv.Itoa(src.Line))
78+
}
79+
6980
return a
7081
}
7182
)
@@ -165,8 +176,9 @@ func New(config *Config) *slog.Logger {
165176
}
166177

167178
logHandlerOpts := &slog.HandlerOptions{
168-
Level: config.Level.lvl,
169-
AddSource: true,
179+
Level: config.Level.lvl,
180+
AddSource: true,
181+
ReplaceAttr: truncateSourceAttrFunc,
170182
}
171183

172184
if config.Style == GoKitStyle {

promslog/slog_test.go

+44
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,47 @@ func TestDynamicLevels(t *testing.T) {
146146
})
147147
}
148148
}
149+
150+
func TestTruncateSourceFileName_DefaultStyle(t *testing.T) {
151+
var buf bytes.Buffer
152+
153+
config := &Config{
154+
Writer: &buf,
155+
}
156+
157+
logger := New(config)
158+
logger.Info("test message")
159+
160+
output := buf.String()
161+
162+
if !strings.Contains(output, "source=slog_test.go:") {
163+
t.Errorf("Expected source file name to be truncated to basename, got: %s", output)
164+
}
165+
166+
if strings.Contains(output, "/") {
167+
t.Errorf("Expected no directory separators in source file name, got: %s", output)
168+
}
169+
}
170+
171+
func TestTruncateSourceFileName_GoKitStyle(t *testing.T) {
172+
var buf bytes.Buffer
173+
174+
config := &Config{
175+
Writer: &buf,
176+
Style: GoKitStyle,
177+
}
178+
179+
logger := New(config)
180+
logger.Info("test message")
181+
182+
output := buf.String()
183+
184+
// In GoKitStyle, the source key is "caller".
185+
if !strings.Contains(output, "caller=slog_test.go:") {
186+
t.Errorf("Expected caller to contain basename of source file, got: %s", output)
187+
}
188+
189+
if strings.Contains(output, "/") {
190+
t.Errorf("Expected no directory separators in caller, got: %s", output)
191+
}
192+
}

0 commit comments

Comments
 (0)