File tree 2 files changed +58
-2
lines changed
2 files changed +58
-2
lines changed Original file line number Diff line number Diff line change 66
66
default :
67
67
}
68
68
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
+
69
80
return a
70
81
}
71
82
)
@@ -165,8 +176,9 @@ func New(config *Config) *slog.Logger {
165
176
}
166
177
167
178
logHandlerOpts := & slog.HandlerOptions {
168
- Level : config .Level .lvl ,
169
- AddSource : true ,
179
+ Level : config .Level .lvl ,
180
+ AddSource : true ,
181
+ ReplaceAttr : truncateSourceAttrFunc ,
170
182
}
171
183
172
184
if config .Style == GoKitStyle {
Original file line number Diff line number Diff line change @@ -146,3 +146,47 @@ func TestDynamicLevels(t *testing.T) {
146
146
})
147
147
}
148
148
}
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
+ }
You can’t perform that action at this time.
0 commit comments