2023-04-02 22:49:45 +03:00
|
|
|
package lg_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-01-27 18:12:02 +03:00
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"log/slog"
|
2023-04-02 22:49:45 +03:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg"
|
2024-01-15 04:45:34 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lgt"
|
2023-04-02 22:49:45 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestContext(t *testing.T) {
|
|
|
|
ctx := context.Background()
|
2024-01-15 04:45:34 +03:00
|
|
|
log := lgt.New(t)
|
2023-04-02 22:49:45 +03:00
|
|
|
|
|
|
|
ctx = lg.NewContext(ctx, log)
|
2023-05-03 15:36:10 +03:00
|
|
|
log = lg.FromContext(ctx)
|
2023-04-02 22:49:45 +03:00
|
|
|
|
|
|
|
log.Info("huzzah")
|
|
|
|
}
|
2024-01-27 18:12:02 +03:00
|
|
|
|
2024-01-28 03:01:45 +03:00
|
|
|
func TestDepth(t *testing.T) {
|
|
|
|
// I'm not motivated enough to write a test that actually checks output
|
|
|
|
// (e.g. by setting the log output to a bytes.Buffer), so this
|
|
|
|
// is just a visual check.
|
2024-01-27 18:12:02 +03:00
|
|
|
log := lgt.New(t)
|
|
|
|
log = log.With("name", "alice", "age", 42)
|
|
|
|
err := errors.New("TestSourceAttr error")
|
|
|
|
|
|
|
|
log.Warn("TestSourceAttr - NO DEPTH")
|
|
|
|
lg.Depth(log, slog.LevelWarn, 0, "TestSourceAttr log depth")
|
|
|
|
lg.WarnIfError(log, "TestSourceAttr", err)
|
|
|
|
lg.WarnIfFuncError(log, "TestSourceAttr", errorFunc)
|
|
|
|
lg.WarnIfCloseError(log, "TestSourceAttr", errorCloser{})
|
|
|
|
lg.Unexpected(log, err)
|
|
|
|
|
|
|
|
nest1(log)
|
|
|
|
}
|
|
|
|
|
|
|
|
func nest1(log *slog.Logger) {
|
|
|
|
err := errors.New("nest1 error")
|
|
|
|
log.Warn("nest1 - NO DEPTH")
|
|
|
|
lg.Depth(log, slog.LevelWarn, 0, "nest1 log depth")
|
|
|
|
lg.WarnIfError(log, "nest1", err)
|
|
|
|
lg.WarnIfFuncError(log, "nest1", errorFunc)
|
|
|
|
lg.WarnIfCloseError(log, "nest1", errorCloser{})
|
|
|
|
lg.Unexpected(log, err)
|
|
|
|
|
|
|
|
nest2(log)
|
|
|
|
}
|
|
|
|
|
|
|
|
func nest2(log *slog.Logger) {
|
|
|
|
err := errors.New("nest2 error")
|
|
|
|
log.Warn("nest2 - NO DEPTH")
|
|
|
|
lg.Depth(log, slog.LevelWarn, 0, "nest2 log depth")
|
|
|
|
lg.WarnIfError(log, "nest2", err)
|
|
|
|
lg.WarnIfFuncError(log, "nest2", errorFunc)
|
|
|
|
lg.WarnIfCloseError(log, "nest2", errorCloser{})
|
|
|
|
lg.Unexpected(log, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func errorFunc() error {
|
|
|
|
return errors.New("errorFunc went bad")
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ io.Closer = errorCloser{}
|
|
|
|
|
|
|
|
type errorCloser struct{}
|
|
|
|
|
|
|
|
func (e errorCloser) Close() error {
|
|
|
|
return errors.New("errorCloser.Close went bad")
|
|
|
|
}
|