Skip to content

Commit 9e06938

Browse files
committed
context/field based logging support go-aah/aah#111
turn off color config for console recevier go-aah/aah#108
1 parent 73f894e commit 9e06938

File tree

10 files changed

+588
-159
lines changed

10 files changed

+588
-159
lines changed

console_receiver.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
package log
66

77
import (
8+
"encoding/json"
89
"fmt"
910
"io"
1011
"os"
1112
"runtime"
13+
"sync"
1214

1315
"aahframework.org/config.v0"
1416
"aahframework.org/essentials.v0"
@@ -38,6 +40,7 @@ type ConsoleReceiver struct {
3840
flags []ess.FmtFlagPart
3941
isCallerInfo bool
4042
isColor bool
43+
mu *sync.Mutex
4144
}
4245

4346
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
@@ -49,11 +52,17 @@ func (c *ConsoleReceiver) Init(cfg *config.Config) error {
4952
c.out = os.Stderr
5053
c.isColor = runtime.GOOS != "windows"
5154

55+
if v, found := cfg.Bool("log.color"); found {
56+
c.isColor = v
57+
}
58+
5259
c.formatter = cfg.StringDefault("log.format", "text")
5360
if !(c.formatter == textFmt || c.formatter == jsonFmt) {
5461
return fmt.Errorf("log: unsupported format '%s'", c.formatter)
5562
}
5663

64+
c.mu = &sync.Mutex{}
65+
5766
return nil
5867
}
5968

@@ -83,12 +92,18 @@ func (c *ConsoleReceiver) IsCallerInfo() bool {
8392

8493
// Log method writes the log entry into os.Stderr.
8594
func (c *ConsoleReceiver) Log(entry *Entry) {
95+
c.mu.Lock()
96+
defer c.mu.Unlock()
97+
8698
if c.isColor {
8799
_, _ = c.out.Write(levelToColor[entry.Level])
88100
}
89101

90-
msg := applyFormatter(c.formatter, c.flags, entry)
91-
if len(msg) == 0 || msg[len(msg)-1] != '\n' {
102+
var msg []byte
103+
if c.formatter == textFmt {
104+
msg = textFormatter(c.flags, entry)
105+
} else {
106+
msg, _ = json.Marshal(entry)
92107
msg = append(msg, '\n')
93108
}
94109
_, _ = c.out.Write(msg)

console_receiver_test.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ func TestConsoleLoggerTextJSON(t *testing.T) {
2020
receiver = "console"
2121
level = "debug"
2222
pattern = "%utctime:2006-01-02 15:04:05.000 %level:-5 %longfile %line %custom:- %message"
23+
color = true
2324
}
2425
`
2526
testConsoleLogger(t, textConfigStr1)
@@ -29,7 +30,7 @@ func TestConsoleLoggerTextJSON(t *testing.T) {
2930
log {
3031
receiver = "console"
3132
level = "debug"
32-
pattern = "%time:2006-01-02 15:04:05.000 %level:-5 %shortfile %line %custom:- %message"
33+
pattern = "%time:2006-01-02 15:04:05.000 %appname %reqid %principal %level:-5 %shortfile %line %custom:- %message"
3334
}
3435
`
3536
testConsoleLogger(t, textConfigStr2)
@@ -112,13 +113,13 @@ func testConsoleLogger(t *testing.T, cfgStr string) {
112113
logger.Trace("I shoudn't see this msg, because standard logger level is DEBUG")
113114
logger.Tracef("I shoudn't see this msg, because standard logger level is DEBUG: %v", 4)
114115

115-
logger.Debug("I would like to see this message, debug is useful for dev")
116+
logger.WithField("appname", "testlogapp").Debug("I would like to see this message, debug is useful for dev")
116117
logger.Debugf("I would like to see this message, debug is useful for %v", "dev")
117118

118-
logger.Info("Yes, I would love to see")
119+
logger.WithField("reqid", "40139CA6368607085BF6").Info("Yes, I would love to see")
119120
logger.Infof("Yes, I would love to %v", "see")
120121

121-
logger.Warn("Yes, yes it's an warning")
122+
logger.WithField("principal", "jeevanandam").Warn("Yes, yes it's an warning")
122123
logger.Warnf("Yes, yes it's an %v", "warning")
123124

124125
logger.Error("Yes, yes, yes - finally an error")
@@ -127,7 +128,7 @@ func testConsoleLogger(t *testing.T, cfgStr string) {
127128
exit = func(code int) {}
128129
logger.Fatal("Yes, yes, yes - at last fatal")
129130
logger.Fatalf("Yes, yes, yes - %v", "at last fatal")
130-
logger.Fatalln("Yes, yes, yes - %v", "at last fatal")
131+
logger.Fatalln("Yes, yes, yes ", "at last fatal")
131132
exit = os.Exit
132133

133134
assert.NotNil(t, logger.ToGoLogger())

default.go

Lines changed: 44 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -5,67 +5,66 @@
55
package log
66

77
import (
8-
"fmt"
98
"io"
109
slog "log"
1110

1211
"aahframework.org/config.v0"
1312
)
1413

15-
var std *Logger
14+
var dl *Logger
1615

1716
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
1817
// Logger methods
1918
//_______________________________________
2019

2120
// Error logs message as `ERROR`. Arguments handled in the mananer of `fmt.Print`.
2221
func Error(v ...interface{}) {
23-
std.output(LevelError, 3, nil, v...)
22+
dl.Error(v...)
2423
}
2524

2625
// Errorf logs message as `ERROR`. Arguments handled in the mananer of `fmt.Printf`.
2726
func Errorf(format string, v ...interface{}) {
28-
std.output(LevelError, 3, &format, v...)
27+
dl.Errorf(format, v...)
2928
}
3029

3130
// Warn logs message as `WARN`. Arguments handled in the mananer of `fmt.Print`.
3231
func Warn(v ...interface{}) {
33-
std.output(LevelWarn, 3, nil, v...)
32+
dl.Warn(v...)
3433
}
3534

3635
// Warnf logs message as `WARN`. Arguments handled in the mananer of `fmt.Printf`.
3736
func Warnf(format string, v ...interface{}) {
38-
std.output(LevelWarn, 3, &format, v...)
37+
dl.Warnf(format, v...)
3938
}
4039

4140
// Info logs message as `INFO`. Arguments handled in the mananer of `fmt.Print`.
4241
func Info(v ...interface{}) {
43-
std.output(LevelInfo, 3, nil, v...)
42+
dl.Info(v...)
4443
}
4544

4645
// Infof logs message as `INFO`. Arguments handled in the mananer of `fmt.Printf`.
4746
func Infof(format string, v ...interface{}) {
48-
std.output(LevelInfo, 3, &format, v...)
47+
dl.Infof(format, v...)
4948
}
5049

5150
// Debug logs message as `DEBUG`. Arguments handled in the mananer of `fmt.Print`.
5251
func Debug(v ...interface{}) {
53-
std.output(LevelDebug, 3, nil, v...)
52+
dl.Debug(v...)
5453
}
5554

5655
// Debugf logs message as `DEBUG`. Arguments handled in the mananer of `fmt.Printf`.
5756
func Debugf(format string, v ...interface{}) {
58-
std.output(LevelDebug, 3, &format, v...)
57+
dl.Debugf(format, v...)
5958
}
6059

6160
// Trace logs message as `TRACE`. Arguments handled in the mananer of `fmt.Print`.
6261
func Trace(v ...interface{}) {
63-
std.output(LevelTrace, 3, nil, v...)
62+
dl.Trace(v...)
6463
}
6564

6665
// Tracef logs message as `TRACE`. Arguments handled in the mananer of `fmt.Printf`.
6766
func Tracef(format string, v ...interface{}) {
68-
std.output(LevelTrace, 3, &format, v...)
67+
dl.Tracef(format, v...)
6968
}
7069

7170
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
@@ -75,78 +74,82 @@ func Tracef(format string, v ...interface{}) {
7574

7675
// Print logs message as `INFO`. Arguments handled in the mananer of `fmt.Print`.
7776
func Print(v ...interface{}) {
78-
std.output(LevelInfo, 3, nil, v...)
77+
dl.Print(v...)
7978
}
8079

8180
// Printf logs message as `INFO`. Arguments handled in the mananer of `fmt.Printf`.
8281
func Printf(format string, v ...interface{}) {
83-
std.output(LevelInfo, 3, &format, v...)
82+
dl.Printf(format, v...)
8483
}
8584

8685
// Println logs message as `INFO`. Arguments handled in the mananer of `fmt.Printf`.
87-
func Println(format string, v ...interface{}) {
88-
std.output(LevelInfo, 3, &format, v...)
86+
func Println(v ...interface{}) {
87+
dl.Println(v...)
8988
}
9089

9190
// Fatal logs message as `FATAL` and call to os.Exit(1).
9291
func Fatal(v ...interface{}) {
93-
std.output(levelFatal, 3, nil, v...)
94-
exit(1)
92+
dl.Fatal(v...)
9593
}
9694

9795
// Fatalf logs message as `FATAL` and call to os.Exit(1).
9896
func Fatalf(format string, v ...interface{}) {
99-
std.output(levelFatal, 3, &format, v...)
100-
exit(1)
97+
dl.Fatalf(format, v...)
10198
}
10299

103100
// Fatalln logs message as `FATAL` and call to os.Exit(1).
104101
func Fatalln(v ...interface{}) {
105-
std.output(levelFatal, 3, nil, v...)
106-
exit(1)
102+
dl.Fatalln(v...)
107103
}
108104

109105
// Panic logs message as `PANIC` and call to panic().
110106
func Panic(v ...interface{}) {
111-
std.output(levelPanic, 3, nil, v...)
112-
panic("")
107+
dl.Panic(v...)
113108
}
114109

115110
// Panicf logs message as `PANIC` and call to panic().
116111
func Panicf(format string, v ...interface{}) {
117-
std.output(levelPanic, 3, &format, v...)
118-
panic(fmt.Sprintf(format, v...))
112+
dl.Panicf(format, v...)
119113
}
120114

121115
// Panicln logs message as `PANIC` and call to panic().
122-
func Panicln(format string, v ...interface{}) {
123-
std.output(levelPanic, 3, &format, v...)
124-
panic(fmt.Sprintf(format, v...))
116+
func Panicln(v ...interface{}) {
117+
dl.Panicln(v...)
118+
}
119+
120+
// WithFields method to add multiple key-value pairs into log.
121+
func WithFields(fields Fields) *Entry {
122+
return dl.WithFields(fields)
123+
}
124+
125+
// WithField method to add single key-value into log
126+
func WithField(key string, value interface{}) *Entry {
127+
return dl.WithField(key, value)
125128
}
126129

127130
// Writer method returns the writer of default logger.
128131
func Writer() io.Writer {
129-
return std.receiver.Writer()
132+
return dl.receiver.Writer()
130133
}
131134

132135
// ToGoLogger method wraps the current log writer into Go Logger instance.
133136
func ToGoLogger() *slog.Logger {
134-
return std.ToGoLogger()
137+
return dl.ToGoLogger()
135138
}
136139

137140
// SetDefaultLogger method sets the given logger instance as default logger.
138141
func SetDefaultLogger(l *Logger) {
139-
std = l
142+
dl = l
140143
}
141144

142145
// SetLevel method sets log level for default logger.
143146
func SetLevel(level string) error {
144-
return std.SetLevel(level)
147+
return dl.SetLevel(level)
145148
}
146149

147150
// SetPattern method sets the log format pattern for default logger.
148151
func SetPattern(pattern string) error {
149-
return std.SetPattern(pattern)
152+
return dl.SetPattern(pattern)
150153
}
151154

152155
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
@@ -155,35 +158,35 @@ func SetPattern(pattern string) error {
155158

156159
// Level method returns currently enabled logging level.
157160
func Level() string {
158-
return std.Level()
161+
return dl.Level()
159162
}
160163

161164
// IsLevelInfo method returns true if log level is INFO otherwise false.
162165
func IsLevelInfo() bool {
163-
return std.IsLevelInfo()
166+
return dl.IsLevelInfo()
164167
}
165168

166169
// IsLevelError method returns true if log level is ERROR otherwise false.
167170
func IsLevelError() bool {
168-
return std.IsLevelError()
171+
return dl.IsLevelError()
169172
}
170173

171174
// IsLevelWarn method returns true if log level is WARN otherwise false.
172175
func IsLevelWarn() bool {
173-
return std.IsLevelWarn()
176+
return dl.IsLevelWarn()
174177
}
175178

176179
// IsLevelDebug method returns true if log level is DEBUG otherwise false.
177180
func IsLevelDebug() bool {
178-
return std.IsLevelDebug()
181+
return dl.IsLevelDebug()
179182
}
180183

181184
// IsLevelTrace method returns true if log level is TRACE otherwise false.
182185
func IsLevelTrace() bool {
183-
return std.IsLevelTrace()
186+
return dl.IsLevelTrace()
184187
}
185188

186189
func init() {
187190
cfg, _ := config.ParseString("log { }")
188-
std, _ = New(cfg)
191+
dl, _ = New(cfg)
189192
}

0 commit comments

Comments
 (0)