File tree Expand file tree Collapse file tree 2 files changed +58
-2
lines changed Expand file tree Collapse file tree 2 files changed +58
-2
lines changed Original file line number Diff line number Diff line change 6666default :
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+
6980return a
7081}
7182)
@@ -165,8 +176,9 @@ func New(config *Config) *slog.Logger {
165176}
166177
167178logHandlerOpts := & slog.HandlerOptions {
168- Level : config .Level .lvl ,
169- AddSource : true ,
179+ Level : config .Level .lvl ,
180+ AddSource : true ,
181+ ReplaceAttr : truncateSourceAttrFunc ,
170182}
171183
172184if config .Style == GoKitStyle {
Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments