Browse Source

Add log format functions (#1)

master
Elwin Tamminga 3 months ago
parent
commit
3540a5778c
2 changed files with 36 additions and 10 deletions
  1. 26
    10
      log.go
  2. 10
    0
      log_test.go

+ 26
- 10
log.go View File

@@ -10,30 +10,46 @@ import (
10 10
 
11 11
 // All log functions
12 12
 var (
13
-	Debug    = logFunc(LevelDebug)
14
-	Info     = logFunc(LevelInfo)
15
-	Warning  = logFunc(LevelWarning)
16
-	Error    = logFunc(LevelError)
17
-	Critical = logFunc(LevelCritical)
13
+	Debug     = logFunc(LevelDebug)
14
+	Debugf    = logfFunc(LevelDebug)
15
+	Info      = logFunc(LevelInfo)
16
+	Infof     = logfFunc(LevelInfo)
17
+	Warning   = logFunc(LevelWarning)
18
+	Warningf  = logfFunc(LevelWarning)
19
+	Error     = logFunc(LevelError)
20
+	Errorf    = logfFunc(LevelError)
21
+	Critical  = logFunc(LevelCritical)
22
+	Criticalf = logfFunc(LevelCritical)
18 23
 )
19 24
 
20 25
 func logFunc(level LevelType) func(...interface{}) {
21 26
 	return func(message ...interface{}) {
22
-		writeMessage(level, message)
27
+		writeMessage(level, ``, message)
28
+	}
29
+}
30
+
31
+func logfFunc(level LevelType) func(string, ...interface{}) {
32
+	return func(format string, a ...interface{}) {
33
+		writeMessage(level, format, a)
23 34
 	}
24 35
 }
25 36
 
26 37
 var mu sync.Mutex
27 38
 
28
-func writeMessage(level LevelType, message []interface{}) {
39
+func writeMessage(level LevelType, format string, message []interface{}) {
29 40
 	if MinLevel > level {
30 41
 		return
31 42
 	}
32 43
 
33 44
 	entry := LogEntry{
34
-		Level:   level,
35
-		Time:    time.Now(),
36
-		Message: fmt.Sprint(message...),
45
+		Level: level,
46
+		Time:  time.Now(),
47
+	}
48
+
49
+	if format == `` {
50
+		entry.Message = fmt.Sprint(message...)
51
+	} else {
52
+		entry.Message = fmt.Sprintf(format, message...)
37 53
 	}
38 54
 
39 55
 	if MinStackLevel <= level {

+ 10
- 0
log_test.go View File

@@ -55,6 +55,16 @@ func TestLogLevel(t *testing.T) {
55 55
 	MinLevel, Output = LevelInfo, nil
56 56
 }
57 57
 
58
+func TestLogf(t *testing.T) {
59
+	b := bytes.Buffer{}
60
+	Output = &b
61
+
62
+	Infof(`Test%s-%d`, `tt`, 1)
63
+	assert.True(t, strings.Contains(b.String(), `Testtt-1`))
64
+
65
+	Output = nil
66
+}
67
+
58 68
 func TestStackTrace(t *testing.T) {
59 69
 	b := bytes.Buffer{}
60 70
 	Output = &b

Loading…
Cancel
Save