ntfy/log/log_test.go

75 lines
1.7 KiB
Go
Raw Normal View History

2023-02-04 03:21:50 +00:00
package log_test
import (
2023-02-06 04:34:27 +00:00
"bytes"
"github.com/stretchr/testify/require"
2023-02-04 03:21:50 +00:00
"heckel.io/ntfy/log"
"net/http"
2023-02-06 04:34:27 +00:00
"os"
2023-02-04 03:21:50 +00:00
"testing"
2023-02-06 04:34:27 +00:00
"time"
2023-02-04 03:21:50 +00:00
)
2023-02-06 04:34:27 +00:00
func TestMain(m *testing.M) {
exitCode := m.Run()
resetState()
log.SetLevel(log.ErrorLevel) // For other modules!
os.Exit(exitCode)
}
func TestLog_TagContextFieldFields(t *testing.T) {
t.Cleanup(resetState)
v := &fakeVisitor{
UserID: "u_abc",
IP: "1.2.3.4",
}
var out bytes.Buffer
log.SetOutput(&out)
log.SetFormat(log.JSONFormat)
log.SetLevelOverride("tag", "stripe", log.DebugLevel)
log.
Tag("mytag").
Field("field2", 123).
Field("field1", "value1").
Time(time.Unix(123, 0)).
Info("hi there %s", "phil")
log.
Tag("not-stripe").
Debug("this message will not appear")
log.
With(v).
Fields(log.Context{
"stripe_customer_id": "acct_123",
"stripe_subscription_id": "sub_123",
}).
Tag("stripe").
Err(http.ErrHandlerTimeout).
Time(time.Unix(456, 0)).
Debug("Subscription status %s", "active")
2023-02-04 03:21:50 +00:00
2023-02-06 04:34:27 +00:00
expected := `{"time":123000,"level":"INFO","message":"hi there phil","field1":"value1","field2":123,"tag":"mytag"}
{"time":456000,"level":"DEBUG","message":"Subscription status active","error":"http: Handler timeout","stripe_customer_id":"acct_123","stripe_subscription_id":"sub_123","tag":"stripe","user_id":"u_abc","visitor_ip":"1.2.3.4"}
`
require.Equal(t, expected, out.String())
}
type fakeVisitor struct {
2023-02-04 03:21:50 +00:00
UserID string
IP string
}
2023-02-06 04:34:27 +00:00
func (v *fakeVisitor) Context() log.Context {
2023-02-04 03:21:50 +00:00
return map[string]any{
2023-02-06 04:34:27 +00:00
"user_id": v.UserID,
"visitor_ip": v.IP,
2023-02-04 03:21:50 +00:00
}
}
2023-02-06 04:34:27 +00:00
func resetState() {
log.SetLevel(log.DefaultLevel)
log.SetFormat(log.DefaultFormat)
log.SetOutput(log.DefaultOutput)
log.ResetLevelOverrides()
2023-02-04 03:21:50 +00:00
}