log.go 6.8 KB
Newer Older
A
astaxie 已提交
1
// Copyright 2014 beego Author. All Rights Reserved.
A
astaxie 已提交
2
//
A
astaxie 已提交
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
A
astaxie 已提交
6
//
A
astaxie 已提交
7
//      http://www.apache.org/licenses/LICENSE-2.0
A
astaxie 已提交
8
//
A
astaxie 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Usage:
//
// import "github.com/astaxie/beego/logs"
//
//	log := NewLogger(10000)
//	log.SetLogger("console", "")
//
//	> the first params stand for how many channel
//
// Use it like this:
//
//	log.Trace("trace")
//	log.Info("info")
//	log.Warn("warning")
//	log.Debug("debug")
//	log.Critical("critical")
A
astaxie 已提交
31
//
A
astaxie 已提交
32
//  more docs http://beego.me/docs/module/logs.md
A
astaxie 已提交
33 34 35 36
package logs

import (
	"fmt"
A
astaxie 已提交
37

A
astaxie 已提交
38 39 40
	"sync"
)

41
// RFC5424 log message levels.
A
astaxie 已提交
42
const (
43 44
	LevelEmergency = iota
	LevelAlert
A
astaxie 已提交
45
	LevelCritical
46 47 48 49 50 51 52 53 54 55 56 57 58 59
	LevelError
	LevelWarning
	LevelNotice
	LevelInformational
	LevelDebug
)

// Legacy loglevel constants to ensure backwards compatibility.
//
// Deprecated: will be removed in 1.5.0.
const (
	LevelInfo  = LevelInformational
	LevelTrace = LevelDebug
	LevelWarn  = LevelWarning
A
astaxie 已提交
60 61 62 63
)

type loggerType func() LoggerInterface

F
FuXiaoHei 已提交
64
// LoggerInterface defines the behavior of a log provider.
A
astaxie 已提交
65 66 67 68
type LoggerInterface interface {
	Init(config string) error
	WriteMsg(msg string, level int) error
	Destroy()
A
astaxie 已提交
69
	Flush()
A
astaxie 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
}

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 已提交
87 88
// BeeLogger is default logger in beego application.
// it can contain several providers and log message into all providers.
A
astaxie 已提交
89
type BeeLogger struct {
A
astaxie 已提交
90 91 92 93
	lock    sync.Mutex
	level   int
	msg     chan *logMsg
	outputs map[string]LoggerInterface
A
astaxie 已提交
94 95 96 97 98 99 100
}

type logMsg struct {
	level int
	msg   string
}

F
FuXiaoHei 已提交
101 102 103
// 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 已提交
104 105
func NewLogger(channellen int64) *BeeLogger {
	bl := new(BeeLogger)
106
	bl.level = LevelDebug
A
astaxie 已提交
107 108
	bl.msg = make(chan *logMsg, channellen)
	bl.outputs = make(map[string]LoggerInterface)
109
	//bl.SetLogger("console", "") // default output to console
A
asta.xie 已提交
110
	go bl.startLogger()
A
astaxie 已提交
111 112 113
	return bl
}

F
FuXiaoHei 已提交
114 115
// SetLogger provides a given logger adapter into BeeLogger with config string.
// config need to be correct JSON as string: {"interval":360}.
A
astaxie 已提交
116 117 118 119 120
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 已提交
121
		err := lg.Init(config)
122
		bl.outputs[adaptername] = lg
A
asta.xie 已提交
123
		if err != nil {
124
			fmt.Println("logs.BeeLogger.SetLogger: " + err.Error())
A
asta.xie 已提交
125 126
			return err
		}
A
astaxie 已提交
127 128 129
	} else {
		return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adaptername)
	}
130
	return nil
A
astaxie 已提交
131 132
}

F
FuXiaoHei 已提交
133
// remove a logger adapter in BeeLogger.
A
astaxie 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146
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 {
147
	if loglevel > bl.level {
A
astaxie 已提交
148 149 150 151
		return nil
	}
	lm := new(logMsg)
	lm.level = loglevel
A
astaxie 已提交
152
	lm.msg = msg
A
astaxie 已提交
153 154 155 156
	bl.msg <- lm
	return nil
}

157 158 159 160
// Set log message level.
//
// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning),
// log providers will not even be sent the message.
A
astaxie 已提交
161 162 163 164
func (bl *BeeLogger) SetLevel(l int) {
	bl.level = l
}

F
FuXiaoHei 已提交
165
// start logger chan reading.
S
stansun 已提交
166
// when chan is not empty, write logs.
A
asta.xie 已提交
167
func (bl *BeeLogger) startLogger() {
A
astaxie 已提交
168 169 170 171
	for {
		select {
		case bm := <-bl.msg:
			for _, l := range bl.outputs {
F
Francois 已提交
172 173 174 175
				err := l.WriteMsg(bm.msg, bm.level)
				if err != nil {
					fmt.Println("ERROR, unable to WriteMsg:", err)
				}
A
astaxie 已提交
176 177 178 179 180
			}
		}
	}
}

181 182
// Log EMERGENCY level message.
func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
183
	msg := fmt.Sprintf("[M] "+format, v...)
184
	bl.writerMsg(LevelEmergency, msg)
A
astaxie 已提交
185 186
}

187 188
// Log ALERT level message.
func (bl *BeeLogger) Alert(format string, v ...interface{}) {
189
	msg := fmt.Sprintf("[A] "+format, v...)
190
	bl.writerMsg(LevelAlert, msg)
A
astaxie 已提交
191 192
}

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
// Log CRITICAL level message.
func (bl *BeeLogger) Critical(format string, v ...interface{}) {
	msg := fmt.Sprintf("[C] "+format, v...)
	bl.writerMsg(LevelCritical, msg)
}

// Log ERROR level message.
func (bl *BeeLogger) Error(format string, v ...interface{}) {
	msg := fmt.Sprintf("[E] "+format, v...)
	bl.writerMsg(LevelError, msg)
}

// Log WARNING level message.
func (bl *BeeLogger) Warning(format string, v ...interface{}) {
	msg := fmt.Sprintf("[W] "+format, v...)
	bl.writerMsg(LevelWarning, msg)
}

// Log NOTICE level message.
func (bl *BeeLogger) Notice(format string, v ...interface{}) {
213
	msg := fmt.Sprintf("[N] "+format, v...)
214 215 216 217 218
	bl.writerMsg(LevelNotice, msg)
}

// Log INFORMATIONAL level message.
func (bl *BeeLogger) Informational(format string, v ...interface{}) {
A
astaxie 已提交
219
	msg := fmt.Sprintf("[I] "+format, v...)
220
	bl.writerMsg(LevelInformational, msg)
A
astaxie 已提交
221 222
}

223 224 225 226 227 228 229 230 231
// Log DEBUG level message.
func (bl *BeeLogger) Debug(format string, v ...interface{}) {
	msg := fmt.Sprintf("[D] "+format, v...)
	bl.writerMsg(LevelDebug, msg)
}

// Log WARN level message.
//
// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
A
astaxie 已提交
232
func (bl *BeeLogger) Warn(format string, v ...interface{}) {
233
	bl.Warning(format, v...)
A
astaxie 已提交
234 235
}

236 237 238 239 240
// Log INFO level message.
//
// Deprecated: compatibility alias for Informational(), Will be removed in 1.5.0.
func (bl *BeeLogger) Info(format string, v ...interface{}) {
	bl.Informational(format, v...)
A
astaxie 已提交
241 242
}

243 244 245 246 247
// Log TRACE level message.
//
// Deprecated: compatibility alias for Debug(), Will be removed in 1.5.0.
func (bl *BeeLogger) Trace(format string, v ...interface{}) {
	bl.Debug(format, v...)
A
astaxie 已提交
248 249
}

F
FuXiaoHei 已提交
250
// flush all chan data.
A
astaxie 已提交
251 252 253 254 255 256
func (bl *BeeLogger) Flush() {
	for _, l := range bl.outputs {
		l.Flush()
	}
}

F
FuXiaoHei 已提交
257
// close logger, flush all chan data and destroy all adapters in BeeLogger.
A
astaxie 已提交
258
func (bl *BeeLogger) Close() {
A
astaxie 已提交
259 260 261 262
	for {
		if len(bl.msg) > 0 {
			bm := <-bl.msg
			for _, l := range bl.outputs {
F
Francois 已提交
263 264 265 266
				err := l.WriteMsg(bm.msg, bm.level)
				if err != nil {
					fmt.Println("ERROR, unable to WriteMsg (while closing logger):", err)
				}
A
astaxie 已提交
267 268 269 270 271
			}
		} else {
			break
		}
	}
A
astaxie 已提交
272
	for _, l := range bl.outputs {
A
astaxie 已提交
273
		l.Flush()
A
astaxie 已提交
274 275 276
		l.Destroy()
	}
}