Skip to content

Commit 884a22c

Browse files
committed
made hooks part of logger itself and godoc update
1 parent 5b54ad3 commit 884a22c

File tree

6 files changed

+67
-78
lines changed

6 files changed

+67
-78
lines changed

default.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ func AddContext(fields Fields) {
123123
dl.AddContext(fields)
124124
}
125125

126+
// AddHook method is to add logger hook function.
127+
func AddHook(name string, hook HookFunc) error {
128+
return dl.AddHook(name, hook)
129+
}
130+
126131
// WithFields method to add multiple key-value pairs into log.
127132
func WithFields(fields Fields) Loggerer {
128133
return dl.WithFields(fields)

default_test.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,11 @@ func TestDefaultContextLogging(t *testing.T) {
9494
exit = os.Exit
9595

9696
// With Context
97-
ctx := dl.New(Fields{
98-
"key1": "key 1 value",
99-
"key2": "key 2 value",
97+
cfg, _ := config.ParseString("log { }")
98+
ctx, _ := NewWithContext(cfg, Fields{
99+
"myname": "logger with context",
100+
"key1": "key 1 value",
101+
"key2": "key 2 value",
100102
})
101103

102104
ctx.Trace("I would like to see this message, trace is more fine grained for dev")
@@ -120,7 +122,7 @@ func TestDefaultContextLogging(t *testing.T) {
120122
ctx.Fatalln("Yes, yes, yes ", "at last fatal")
121123
exit = os.Exit
122124

123-
ctx2 := WithFields(Fields{"ctx2": "ctx 2 value"})
125+
ctx2 := dl.New(Fields{"ctx2": "ctx 2 value"})
124126
ctx2.Print("hi fields")
125127
}
126128

formatter.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,13 @@ var (
5858
// 2006-01-02 15:04:05.000 INFO This is my message
5959
DefaultPattern = "%time:2006-01-02 15:04:05.000 %level:-5 %message"
6060

61-
// FmtFlags is the list of log format flags supported by aah/log library
61+
// FmtFlags is the list of log format flags supported by aah log library
6262
// Usage of flag order is up to format composition.
63-
// level - outputs INFO, DEBUG, ERROR, so on
63+
// level - outputs ERROR, WARN, INFO, DEBUG, TRACE
6464
// appname - outputs Application Name
6565
// insname - outputs Application Instance Name
6666
// reqid - outputs Request ID from HTTP header
67-
// principal - outputs Logged-In subject primary principal
68-
// level - outputs INFO, DEBUG, ERROR, so on
67+
// principal - outputs Logged-In subject primary principal value
6968
// time - outputs local time as per format supplied
7069
// utctime - outputs UTC time as per format supplied
7170
// longfile - outputs full file name: /a/b/c/d.go

hook.go

Lines changed: 0 additions & 54 deletions
This file was deleted.

hook_test.go

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -37,28 +37,23 @@ func TestLogAddHook(t *testing.T) {
3737
}
3838

3939
func TestLogHook(t *testing.T) {
40-
// Add hook
41-
_ = AddHook("hook1", func(e Entry) {
42-
assert.NotNil(t, e)
43-
fmt.Println(e)
44-
})
45-
4640
configStr := `
4741
log {
4842
receiver = "console"
4943
level = "debug"
5044
pattern = "%utctime:2006-01-02 15:04:05.000 %level:-5 %line %custom:- %message"
5145
}
5246
`
53-
testHooks(t, configStr)
54-
time.Sleep(1 * time.Millisecond)
55-
}
56-
57-
func testHooks(t *testing.T, cfgStr string) {
58-
cfg, _ := config.ParseString(cfgStr)
47+
cfg, _ := config.ParseString(configStr)
5948
logger, err := New(cfg)
6049
assert.FailNowOnError(t, err, "unexpected error")
6150

51+
// Add hook
52+
_ = logger.AddHook("hook1", func(e Entry) {
53+
assert.NotNil(t, e)
54+
fmt.Println(e)
55+
})
56+
6257
logger.Trace("I shoudn't see this msg, because standard logger level is DEBUG")
6358
logger.Debug("I would like to see this message, debug is useful for dev")
6459
logger.Info("Yes, I would love to see")
@@ -69,5 +64,5 @@ func testHooks(t *testing.T, cfgStr string) {
6964
logger.Fatal("Yes, yes, yes - at last fatal")
7065
exit = os.Exit
7166

72-
assert.NotNil(t, logger.ToGoLogger())
67+
time.Sleep(1 * time.Millisecond)
7368
}

log.go

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ import (
3636
// Level type definition
3737
type level uint8
3838

39+
// HookFunc type is aah framework logger custom hook.
40+
type HookFunc func(e Entry)
41+
3942
// Log Level definition
4043
const (
4144
levelFatal level = iota
@@ -52,6 +55,9 @@ var (
5255
// ErrLogReceiverIsNil returned when suppiled receiver is nil.
5356
ErrLogReceiverIsNil = errors.New("log: receiver is nil")
5457

58+
// ErrHookFuncIsNil is returned when hook function is nil.
59+
ErrHookFuncIsNil = errors.New("log: hook func is nil")
60+
5561
filePermission = os.FileMode(0755)
5662

5763
// abstract it, can be unit tested
@@ -66,10 +72,11 @@ type (
6672
// it guarantees to serialize access to the Receivers.
6773
Logger struct {
6874
cfg *config.Config
69-
m *sync.Mutex
75+
m *sync.RWMutex
7076
level level
7177
receiver Receiver
7278
ctx Fields
79+
hooks map[string]HookFunc
7380
}
7481

7582
// Receiver is the interface for pluggable log receiver.
@@ -123,7 +130,7 @@ func New(cfg *config.Config) (*Logger, error) {
123130
return nil, errors.New("log: config is nil")
124131
}
125132

126-
logger := &Logger{m: &sync.Mutex{}, cfg: cfg}
133+
logger := &Logger{m: &sync.RWMutex{}, cfg: cfg}
127134

128135
// Receiver
129136
receiverType := strings.ToUpper(cfg.StringDefault("log.receiver", "CONSOLE"))
@@ -142,10 +149,21 @@ func New(cfg *config.Config) (*Logger, error) {
142149
}
143150

144151
logger.ctx = make(Fields)
152+
logger.hooks = make(map[string]HookFunc)
145153

146154
return logger, nil
147155
}
148156

157+
// NewWithContext method creates the aah logger based on supplied `config.Config`.
158+
func NewWithContext(cfg *config.Config, ctx Fields) (*Logger, error) {
159+
l, err := New(cfg)
160+
if err != nil {
161+
return nil, err
162+
}
163+
l.AddContext(ctx)
164+
return l, nil
165+
}
166+
149167
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
150168
// Logger methods
151169
//___________________________________
@@ -169,6 +187,22 @@ func (l *Logger) AddContext(fields Fields) {
169187
}
170188
}
171189

190+
// AddHook method is to add logger hook function.
191+
func (l *Logger) AddHook(name string, hook HookFunc) error {
192+
if hook == nil {
193+
return ErrHookFuncIsNil
194+
}
195+
196+
l.m.Lock()
197+
defer l.m.Unlock()
198+
if _, found := l.hooks[name]; found {
199+
return fmt.Errorf("log: hook name '%v' is already added, skip it", name)
200+
}
201+
202+
l.hooks[name] = hook
203+
return nil
204+
}
205+
172206
// Level method returns currently enabled logging level.
173207
func (l *Logger) Level() string {
174208
return levelToLevelName[l.level]
@@ -442,5 +476,13 @@ func (l *Logger) output(e *Entry) {
442476
l.receiver.Log(e)
443477

444478
// Execute logger hooks
445-
go executeHooks(*e)
479+
go l.executeHooks(*e)
480+
}
481+
482+
func (l *Logger) executeHooks(e Entry) {
483+
l.m.RLock()
484+
defer l.m.RUnlock()
485+
for _, fn := range l.hooks {
486+
go fn(e)
487+
}
446488
}

0 commit comments

Comments
 (0)