Files
kopia/internal/testlogging/ctx.go
Jarek Kowalski 70e24106ee refactor(general): unified logging.Logger with *zap.SugaredLogger (#2090)
- removed a bunch of hacks and should improve the logging
performance by avoiding interfaces and data translation. This will
allow using of de-sugared loggers in performance-critical
logging situations.

- this will also allow using features of ZAP more directly without
having to reimplement them.

- moved logging.Printf() to testlogging

- refactored `uitask` to store logs in a structural format and
present them as JSON only in the UI

- renamed printf_logger.go to printf.go so that fewer columns are used
in the logs
2022-06-26 05:11:52 +00:00

62 lines
1.9 KiB
Go

// Package testlogging implements logger that writes to testing.T log.
package testlogging
import (
"context"
"testing"
"go.uber.org/zap/zapcore"
"github.com/kopia/kopia/repo/logging"
)
type testingT interface {
Helper()
Errorf(string, ...interface{})
Fatalf(string, ...interface{})
Logf(string, ...interface{})
}
// Level specifies log level.
type Level = zapcore.Level
// log levels.
const (
LevelDebug = zapcore.DebugLevel
LevelInfo = zapcore.InfoLevel
LevelWarn = zapcore.WarnLevel
LevelError = zapcore.ErrorLevel
)
// NewTestLogger returns logger bound to the provided testing.T.
// nolint:thelper
func NewTestLogger(t *testing.T) logging.Logger {
return Printf(t.Logf, "")
}
// Context returns a context with attached logger that emits all log entries to go testing.T log output.
func Context(t testingT) context.Context {
return ContextWithLevel(t, LevelDebug)
}
// ContextWithLevel returns a context with attached logger that emits all log entries with given log level or above.
func ContextWithLevel(t testingT, level Level) context.Context {
return logging.WithLogger(context.Background(), func(module string) logging.Logger {
return PrintfLevel(t.Logf, "["+module+"] ", level)
})
}
// ContextWithLevelAndPrefix returns a context with attached logger that emits all log entries with given log level or above.
func ContextWithLevelAndPrefix(t testingT, level Level, prefix string) context.Context {
return logging.WithLogger(context.Background(), func(module string) logging.Logger {
return PrintfLevel(t.Logf, "["+module+"] "+prefix, level)
})
}
// ContextWithLevelAndPrefixFunc returns a context with attached logger that emits all log entries with given log level or above.
func ContextWithLevelAndPrefixFunc(t testingT, level Level, prefixFunc func() string) context.Context {
return logging.WithLogger(context.Background(), func(module string) logging.Logger {
return PrintfLevel(t.Logf, "["+module+"] "+prefixFunc(), level)
})
}