log.go 4.9 KB
Newer Older
A
astaxie 已提交
1 2 3 4
package logs

import (
	"fmt"
A
asta.xie 已提交
5 6
	"path"
	"runtime"
A
astaxie 已提交
7 8 9 10
	"sync"
)

const (
F
FuXiaoHei 已提交
11
	// log message levels
A
astaxie 已提交
12 13 14 15 16 17 18 19 20 21
	LevelTrace = iota
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelCritical
)

type loggerType func() LoggerInterface

F
FuXiaoHei 已提交
22
// LoggerInterface defines the behavior of a log provider.
A
astaxie 已提交
23 24 25 26
type LoggerInterface interface {
	Init(config string) error
	WriteMsg(msg string, level int) error
	Destroy()
A
astaxie 已提交
27
	Flush()
A
astaxie 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
}

var adapters = make(map[string]loggerType)

// Register makes a log provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, log loggerType) {
	if log == nil {
		panic("logs: Register provide is nil")
	}
	if _, dup := adapters[name]; dup {
		panic("logs: Register called twice for provider " + name)
	}
	adapters[name] = log
}

F
FuXiaoHei 已提交
45 46
// BeeLogger is default logger in beego application.
// it can contain several providers and log message into all providers.
A
astaxie 已提交
47
type BeeLogger struct {
A
asta.xie 已提交
48 49 50 51 52 53
	lock                sync.Mutex
	level               int
	enableFuncCallDepth bool
	loggerFuncCallDepth int
	msg                 chan *logMsg
	outputs             map[string]LoggerInterface
A
astaxie 已提交
54 55 56 57 58 59 60
}

type logMsg struct {
	level int
	msg   string
}

F
FuXiaoHei 已提交
61 62 63
// NewLogger returns a new BeeLogger.
// channellen means the number of messages in chan.
// if the buffering chan is full, logger adapters write to file or other way.
A
astaxie 已提交
64 65
func NewLogger(channellen int64) *BeeLogger {
	bl := new(BeeLogger)
A
asta.xie 已提交
66
	bl.loggerFuncCallDepth = 2
A
astaxie 已提交
67 68
	bl.msg = make(chan *logMsg, channellen)
	bl.outputs = make(map[string]LoggerInterface)
69
	//bl.SetLogger("console", "") // default output to console
A
asta.xie 已提交
70
	go bl.startLogger()
A
astaxie 已提交
71 72 73
	return bl
}

F
FuXiaoHei 已提交
74 75
// SetLogger provides a given logger adapter into BeeLogger with config string.
// config need to be correct JSON as string: {"interval":360}.
A
astaxie 已提交
76 77 78 79 80
func (bl *BeeLogger) SetLogger(adaptername string, config string) error {
	bl.lock.Lock()
	defer bl.lock.Unlock()
	if log, ok := adapters[adaptername]; ok {
		lg := log()
A
asta.xie 已提交
81 82 83 84
		err := lg.Init(config)
		if err != nil {
			return err
		}
A
astaxie 已提交
85 86 87 88 89 90 91
		bl.outputs[adaptername] = lg
		return nil
	} else {
		return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adaptername)
	}
}

F
FuXiaoHei 已提交
92
// remove a logger adapter in BeeLogger.
A
astaxie 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
func (bl *BeeLogger) DelLogger(adaptername string) error {
	bl.lock.Lock()
	defer bl.lock.Unlock()
	if lg, ok := bl.outputs[adaptername]; ok {
		lg.Destroy()
		delete(bl.outputs, adaptername)
		return nil
	} else {
		return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adaptername)
	}
}

func (bl *BeeLogger) writerMsg(loglevel int, msg string) error {
	if bl.level > loglevel {
		return nil
	}
	lm := new(logMsg)
	lm.level = loglevel
A
asta.xie 已提交
111 112 113 114 115 116 117 118 119 120 121
	if bl.enableFuncCallDepth {
		_, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth)
		if ok {
			_, filename := path.Split(file)
			lm.msg = fmt.Sprintf("[%s:%d] %s", filename, line, msg)
		} else {
			lm.msg = msg
		}
	} else {
		lm.msg = msg
	}
A
astaxie 已提交
122 123 124 125
	bl.msg <- lm
	return nil
}

F
FuXiaoHei 已提交
126 127
// set log message level.
// if message level (such as LevelTrace) is less than logger level (such as LevelWarn), ignore message.
A
astaxie 已提交
128 129 130 131
func (bl *BeeLogger) SetLevel(l int) {
	bl.level = l
}

A
asta.xie 已提交
132 133 134 135 136 137 138 139 140 141
// set log funcCallDepth
func (bl *BeeLogger) SetLogFuncCallDepth(d int) {
	bl.loggerFuncCallDepth = d
}

// enable log funcCallDepth
func (bl *BeeLogger) EnableFuncCallDepth(b bool) {
	bl.enableFuncCallDepth = b
}

F
FuXiaoHei 已提交
142 143
// start logger chan reading.
// when chan is full, write logs.
A
asta.xie 已提交
144
func (bl *BeeLogger) startLogger() {
A
astaxie 已提交
145 146 147 148 149 150 151 152 153 154
	for {
		select {
		case bm := <-bl.msg:
			for _, l := range bl.outputs {
				l.WriteMsg(bm.msg, bm.level)
			}
		}
	}
}

F
FuXiaoHei 已提交
155
// log trace level message.
A
astaxie 已提交
156 157 158 159 160
func (bl *BeeLogger) Trace(format string, v ...interface{}) {
	msg := fmt.Sprintf("[T] "+format, v...)
	bl.writerMsg(LevelTrace, msg)
}

F
FuXiaoHei 已提交
161
// log debug level message.
A
astaxie 已提交
162 163 164 165 166
func (bl *BeeLogger) Debug(format string, v ...interface{}) {
	msg := fmt.Sprintf("[D] "+format, v...)
	bl.writerMsg(LevelDebug, msg)
}

F
FuXiaoHei 已提交
167
// log info level message.
A
astaxie 已提交
168 169 170 171 172
func (bl *BeeLogger) Info(format string, v ...interface{}) {
	msg := fmt.Sprintf("[I] "+format, v...)
	bl.writerMsg(LevelInfo, msg)
}

F
FuXiaoHei 已提交
173
// log warn level message.
A
astaxie 已提交
174 175 176 177 178
func (bl *BeeLogger) Warn(format string, v ...interface{}) {
	msg := fmt.Sprintf("[W] "+format, v...)
	bl.writerMsg(LevelWarn, msg)
}

F
FuXiaoHei 已提交
179
// log error level message.
A
astaxie 已提交
180 181 182 183 184
func (bl *BeeLogger) Error(format string, v ...interface{}) {
	msg := fmt.Sprintf("[E] "+format, v...)
	bl.writerMsg(LevelError, msg)
}

F
FuXiaoHei 已提交
185
// log critical level message.
A
astaxie 已提交
186 187 188 189 190
func (bl *BeeLogger) Critical(format string, v ...interface{}) {
	msg := fmt.Sprintf("[C] "+format, v...)
	bl.writerMsg(LevelCritical, msg)
}

F
FuXiaoHei 已提交
191
// flush all chan data.
A
astaxie 已提交
192 193 194 195 196 197
func (bl *BeeLogger) Flush() {
	for _, l := range bl.outputs {
		l.Flush()
	}
}

F
FuXiaoHei 已提交
198
// close logger, flush all chan data and destroy all adapters in BeeLogger.
A
astaxie 已提交
199
func (bl *BeeLogger) Close() {
A
astaxie 已提交
200 201 202 203 204 205 206 207 208 209
	for {
		if len(bl.msg) > 0 {
			bm := <-bl.msg
			for _, l := range bl.outputs {
				l.WriteMsg(bm.msg, bm.level)
			}
		} else {
			break
		}
	}
A
astaxie 已提交
210
	for _, l := range bl.outputs {
A
astaxie 已提交
211
		l.Flush()
A
astaxie 已提交
212 213 214
		l.Destroy()
	}
}