From 101efdd2e7ba87ebdfd414b3e62a276c5871a9cd Mon Sep 17 00:00:00 2001 From: Gusted Date: Wed, 5 Mar 2025 00:10:46 +0100 Subject: [PATCH] fix: correct logging if caller has generics - If the caller function has generics then `runtime.FuncForPC(...).Name()` will not show the generic types and instead collapse it to `[...]`. Remove this suffix from the function name. - This fixes an issue where the logging of functions that use generics such as `db.Find` to be logged as `]()` instead of `Find()`, as the last dot in `[...]` was being used as a cutoff point. - Unit test added. --- modules/log/logger_impl.go | 2 +- modules/log/logger_impl_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 modules/log/logger_impl_test.go diff --git a/modules/log/logger_impl.go b/modules/log/logger_impl.go index d38c6516ed..77e7edf6aa 100644 --- a/modules/log/logger_impl.go +++ b/modules/log/logger_impl.go @@ -191,7 +191,7 @@ func (l *LoggerImpl) Log(skip int, level Level, format string, logArgs ...any) { if ok { fn := runtime.FuncForPC(pc) if fn != nil { - event.Caller = fn.Name() + "()" + event.Caller = strings.TrimSuffix(fn.Name(), "[...]") + "()" } } event.Filename, event.Line = strings.TrimPrefix(filename, projectPackagePrefix), line diff --git a/modules/log/logger_impl_test.go b/modules/log/logger_impl_test.go new file mode 100644 index 0000000000..59276a83f4 --- /dev/null +++ b/modules/log/logger_impl_test.go @@ -0,0 +1,27 @@ +// Copyright 2025 The Forgejo Authors. All rights reserved. +// SPDX-License-Identifier: GPL-3.0-or-later + +package log + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func testGeneric[T any](log *LoggerImpl, t T) { + log.Log(0, INFO, "Just testing the logging of a generic function %v", t) +} + +func TestLog(t *testing.T) { + bufferWriter := NewEventWriterBuffer("test-buffer", WriterMode{ + Level: INFO, + }) + + logger := NewLoggerWithWriters(t.Context(), "test", bufferWriter) + + testGeneric(logger, "I'm the generic value!") + logger.Close() + + assert.Contains(t, bufferWriter.Buffer.String(), ".../logger_impl_test.go:13:testGeneric() [I] Just testing the logging of a generic function I'm the generic value!") +}