diff --git a/handle.go b/handle.go index 7836203..083cd78 100644 --- a/handle.go +++ b/handle.go @@ -91,7 +91,7 @@ func CreateHttpHandler(handlers Handlers) func(http.ResponseWriter, *http.Reques start := time.Now() logger.Debugf("Skill execution started") if req.Event.Type != "sync-request" { - logger.Debugf("Incoming event message: %s", sanitizeEvent(body)) + logger.Debugf("Incoming event message: %s", func() interface{} { return sanitizeEvent(body) }) } defer func() { diff --git a/log.go b/log.go index 3cd2c38..f7852da 100644 --- a/log.go +++ b/log.go @@ -147,6 +147,7 @@ func createLogger(ctx context.Context, event EventIncoming, headers http.Header) doGcpLog(msg, internal.Debug) } logger.Debugf = func(format string, a ...any) { + a = expandFuncs(a, logrus.DebugLevel) Log.WithFields(localLabels).Debugf(format, a...) doGcpLog(fmt.Sprintf(format, a...), internal.Debug) } @@ -185,6 +186,16 @@ func createLogger(ctx context.Context, event EventIncoming, headers http.Header) return logger } +func expandFuncs(a []any, level logrus.Level) []any { + for i, v := range a { + if f, ok := v.(func() interface{}); ok && Log.Level >= level { + a[i] = f() + } + } + + return a +} + // SanitizeEvent removes any sensitive information from the incoming payload structure func sanitizeEvent(incoming string) string { re, _ := regexp.Compile(`:([a-z\.\/-]*)\s*"(.*?)"`) diff --git a/log_test.go b/log_test.go index 6298311..cb0e4c4 100644 --- a/log_test.go +++ b/log_test.go @@ -17,6 +17,7 @@ package skill import ( + "bytes" "context" "net/http" "net/http/httptest" @@ -24,6 +25,7 @@ import ( "testing" "github.com/atomist-skills/go-skill/internal" + "github.com/sirupsen/logrus" "olympos.io/encoding/edn" ) @@ -91,3 +93,15 @@ func TestSanitizeEventWithSingleCharacterUser(t *testing.T) { t.Errorf("user not sanitised") } } + +func TestLoggingWithFunc(t *testing.T) { + var buf bytes.Buffer + Log.SetOutput(&buf) + Log.SetLevel(logrus.DebugLevel) + logger := createLogger(context.Background(), EventIncoming{}, http.Header{}) + logger.Debugf("This is a %s message", func() interface{} { return "test" }) + + if !strings.Contains(buf.String(), "This is a test message") { + t.Errorf("Expected message not found") + } +}