ntfy/log/log_test.go

94 lines
1.9 KiB
Go
Raw Normal View History

2023-02-04 04:21:50 +01:00
package log_test
import (
2023-02-06 05:34:27 +01:00
"bytes"
"github.com/stretchr/testify/require"
2023-02-04 04:21:50 +01:00
"heckel.io/ntfy/log"
2023-02-06 05:34:27 +01:00
"os"
2023-02-04 04:21:50 +01:00
"testing"
2023-02-06 05:34:27 +01:00
"time"
2023-02-04 04:21:50 +01:00
)
2023-02-06 05:34:27 +01: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",
}
2023-02-06 22:01:32 +01:00
err := &fakeError{
Code: 123,
Message: "some error",
}
2023-02-06 05:34:27 +01:00
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").
2023-02-06 22:01:32 +01:00
Err(err).
2023-02-06 05:34:27 +01:00
Time(time.Unix(456, 0)).
Debug("Subscription status %s", "active")
2023-02-04 04:21:50 +01:00
2023-02-06 05:34:27 +01:00
expected := `{"time":123000,"level":"INFO","message":"hi there phil","field1":"value1","field2":123,"tag":"mytag"}
2023-02-06 22:01:32 +01:00
{"time":456000,"level":"DEBUG","message":"Subscription status active","error":"some error","error_code":123,"stripe_customer_id":"acct_123","stripe_subscription_id":"sub_123","tag":"stripe","user_id":"u_abc","visitor_ip":"1.2.3.4"}
2023-02-06 05:34:27 +01:00
`
require.Equal(t, expected, out.String())
}
2023-02-06 22:01:32 +01:00
type fakeError struct {
Code int
Message string
}
func (e fakeError) Error() string {
return e.Message
}
func (e fakeError) Context() log.Context {
return log.Context{
"error": e.Message,
"error_code": e.Code,
}
}
2023-02-06 05:34:27 +01:00
type fakeVisitor struct {
2023-02-04 04:21:50 +01:00
UserID string
IP string
}
2023-02-06 05:34:27 +01:00
func (v *fakeVisitor) Context() log.Context {
2023-02-06 22:01:32 +01:00
return log.Context{
2023-02-06 05:34:27 +01:00
"user_id": v.UserID,
"visitor_ip": v.IP,
2023-02-04 04:21:50 +01:00
}
}
2023-02-06 05:34:27 +01:00
func resetState() {
log.SetLevel(log.DefaultLevel)
log.SetFormat(log.DefaultFormat)
log.SetOutput(log.DefaultOutput)
log.ResetLevelOverrides()
2023-02-04 04:21:50 +01:00
}