2
0
mirror of https://github.com/hibiken/asynq.git synced 2025-08-25 07:01:34 +08:00

Change LogLevel to satisfy flag.Value interface

This commit is contained in:
Ken Hibino
2020-05-09 10:59:50 -07:00
parent 00b82904c6
commit 73d62844e6
4 changed files with 129 additions and 6 deletions

View File

@@ -13,7 +13,7 @@ import (
"sync"
)
// Base supports logging with various log levels.
// Base supports logging at various log levels.
type Base interface {
// Debug logs a message at Debug level.
Debug(args ...interface{})
@@ -87,7 +87,7 @@ func NewLogger(base Base) *Logger {
return &Logger{base: base, level: DebugLevel}
}
// Logger logs message to io.Writer with various log levels.
// Logger logs message to io.Writer at various log levels.
type Logger struct {
base Base
@@ -121,6 +121,9 @@ const (
FatalLevel
)
// String is part of the fmt.Stringer interface.
//
// Used for testing and debugging purposes.
func (l Level) String() string {
switch l {
case DebugLevel:
@@ -167,14 +170,14 @@ func (l *Logger) Warn(args ...interface{}) {
}
func (l *Logger) Error(args ...interface{}) {
if !l.canLogAt(WarnLevel) {
if !l.canLogAt(ErrorLevel) {
return
}
l.base.Error(args...)
}
func (l *Logger) Fatal(args ...interface{}) {
if !l.canLogAt(WarnLevel) {
if !l.canLogAt(FatalLevel) {
return
}
l.base.Fatal(args...)

View File

@@ -284,7 +284,9 @@ func TestLoggerErrorf(t *testing.T) {
}
}
func TestLoggerWithMinLevels(t *testing.T) {
func TestLoggerWithLowerLevels(t *testing.T) {
// Logger should not log messages at a level
// lower than the specified level.
tests := []struct {
level Level
op string
@@ -334,3 +336,53 @@ func TestLoggerWithMinLevels(t *testing.T) {
}
}
}
func TestLoggerWithSameOrHigherLevels(t *testing.T) {
// Logger should log messages at a level
// same as or higher than the specified level.
tests := []struct {
level Level
op string
}{
// same level
{DebugLevel, "Debug"},
{InfoLevel, "Infof"},
{WarnLevel, "Warn"},
{ErrorLevel, "Errorf"},
// higher level
{DebugLevel, "Info"},
{InfoLevel, "Warnf"},
{WarnLevel, "Error"},
}
for _, tc := range tests {
var buf bytes.Buffer
logger := NewLogger(newBase(&buf))
logger.SetLevel(tc.level)
switch tc.op {
case "Debug":
logger.Debug("hello")
case "Debugf":
logger.Debugf("hello, %s", "world")
case "Info":
logger.Info("hello")
case "Infof":
logger.Infof("hello, %s", "world")
case "Warn":
logger.Warn("hello")
case "Warnf":
logger.Warnf("hello, %s", "world")
case "Error":
logger.Error("hello")
case "Errorf":
logger.Errorf("hello, %s", "world")
default:
t.Fatalf("unexpected op: %q", tc.op)
}
if buf.String() == "" {
t.Errorf("logger.%s did not output log message when level is set to %v", tc.op, tc.level)
}
}
}