1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 22:51:29 +00:00
This commit is contained in:
youngsterxyf 2016-01-23 16:24:58 +08:00
parent af346e871b
commit ecf24640fd
6 changed files with 88 additions and 68 deletions

View File

@ -19,6 +19,7 @@ import (
"io" "io"
"log" "log"
"net" "net"
"time"
) )
// connWriter implements LoggerInterface. // connWriter implements LoggerInterface.
@ -48,7 +49,7 @@ func (c *connWriter) Init(jsonconfig string) error {
// WriteMsg write message in connection. // WriteMsg write message in connection.
// if connection is down, try to re-connect. // if connection is down, try to re-connect.
func (c *connWriter) WriteMsg(msg string, level int) error { func (c *connWriter) WriteMsg(when time.Time, msg string, level int) error {
if level > c.Level { if level > c.Level {
return nil return nil
} }
@ -62,6 +63,10 @@ func (c *connWriter) WriteMsg(msg string, level int) error {
if c.ReconnectOnMsg { if c.ReconnectOnMsg {
defer c.innerWriter.Close() defer c.innerWriter.Close()
} }
logTimeStr := formatLogTime(when)
msg = logTimeStr + msg
c.lg.Println(msg) c.lg.Println(msg)
return nil return nil
} }
@ -94,7 +99,7 @@ func (c *connWriter) connect() error {
} }
c.innerWriter = conn c.innerWriter = conn
c.lg = log.New(conn, "", log.Ldate|log.Ltime) c.lg = log.New(conn, "", 0)
return nil return nil
} }

View File

@ -19,6 +19,7 @@ import (
"log" "log"
"os" "os"
"runtime" "runtime"
"time"
) )
// brush is a color join function // brush is a color join function
@ -53,7 +54,7 @@ type consoleWriter struct {
// NewConsole create ConsoleWriter returning as LoggerInterface. // NewConsole create ConsoleWriter returning as LoggerInterface.
func NewConsole() Logger { func NewConsole() Logger {
cw := &consoleWriter{ cw := &consoleWriter{
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime), lg: log.New(os.Stdout, "", 0),
Level: LevelDebug, Level: LevelDebug,
} }
return cw return cw
@ -69,10 +70,14 @@ func (c *consoleWriter) Init(jsonconfig string) error {
} }
// WriteMsg write message in console. // WriteMsg write message in console.
func (c *consoleWriter) WriteMsg(msg string, level int) error { func (c *consoleWriter) WriteMsg(when time.Time, msg string, level int) error {
if level > c.Level { if level > c.Level {
return nil return nil
} }
logTimeStr := formatLogTime(when)
msg = logTimeStr + msg
if goos := runtime.GOOS; goos == "windows" { if goos := runtime.GOOS; goos == "windows" {
c.lg.Println(msg) c.lg.Println(msg)
return nil return nil

View File

@ -48,16 +48,16 @@ func (el *esLogger) Init(jsonconfig string) error {
} }
// WriteMsg will write the msg and level into es // WriteMsg will write the msg and level into es
func (el *esLogger) WriteMsg(msg string, level int) error { func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
if level > el.Level { if level > el.Level {
return nil return nil
} }
t := time.Now()
vals := make(map[string]interface{}) vals := make(map[string]interface{})
vals["@timestamp"] = t.Format(time.RFC3339) vals["@timestamp"] = when.Format(time.RFC3339)
vals["@msg"] = msg vals["@msg"] = msg
d := goes.Document{ d := goes.Document{
Index: fmt.Sprintf("%04d.%02d.%02d", t.Year(), t.Month(), t.Day()), Index: fmt.Sprintf("%04d.%02d.%02d", when.Year(), when.Month(), when.Day()),
Type: "logs", Type: "logs",
Fields: vals, Fields: vals,
} }

View File

@ -114,50 +114,15 @@ func (w *fileLogWriter) needRotate(size int, day int) bool {
} }
// WriteMsg write logger message into file. // WriteMsg write logger message into file.
func (w *fileLogWriter) WriteMsg(msg string, level int) error { func (w *fileLogWriter) WriteMsg(when time.Time, msg string, level int) error {
if level > w.Level { if level > w.Level {
return nil return nil
} }
//2016/01/12 21:34:33 //2016/01/12 21:34:33
now := time.Now() // now := time.Now()
y, mo, d := now.Date() d := when.Day()
h, mi, s := now.Clock() logTimeStr := formatLogTime(when)
//len(2006/01/02 15:03:04)==19 msg = logTimeStr + msg + "\n"
var buf [20]byte
t := 3
for y >= 10 {
p := y / 10
buf[t] = byte('0' + y - p*10)
y = p
t--
}
buf[0] = byte('0' + y)
buf[4] = '/'
if mo > 9 {
buf[5] = '1'
buf[6] = byte('0' + mo - 9)
} else {
buf[5] = '0'
buf[6] = byte('0' + mo)
}
buf[7] = '/'
t = d / 10
buf[8] = byte('0' + t)
buf[9] = byte('0' + d - t*10)
buf[10] = ' '
t = h / 10
buf[11] = byte('0' + t)
buf[12] = byte('0' + h - t*10)
buf[13] = ':'
t = mi / 10
buf[14] = byte('0' + t)
buf[15] = byte('0' + mi - t*10)
buf[16] = ':'
t = s / 10
buf[17] = byte('0' + t)
buf[18] = byte('0' + s - t*10)
buf[19] = ' '
msg = string(buf[0:]) + msg + "\n"
if w.Rotate { if w.Rotate {
if w.needRotate(len(msg), d) { if w.needRotate(len(msg), d) {

View File

@ -40,6 +40,7 @@ import (
"runtime" "runtime"
"strconv" "strconv"
"sync" "sync"
"time"
) )
// RFC5424 log message levels. // RFC5424 log message levels.
@ -68,7 +69,7 @@ type loggerType func() Logger
// Logger defines the behavior of a log provider. // Logger defines the behavior of a log provider.
type Logger interface { type Logger interface {
Init(config string) error Init(config string) error
WriteMsg(msg string, level int) error WriteMsg(when time.Time, msg string, level int) error
Destroy() Destroy()
Flush() Flush()
} }
@ -108,6 +109,7 @@ type nameLogger struct {
type logMsg struct { type logMsg struct {
level int level int
msg string msg string
when time.Time
} }
var logMsgPool *sync.Pool var logMsgPool *sync.Pool
@ -173,16 +175,16 @@ func (bl *BeeLogger) DelLogger(adapterName string) error {
return nil return nil
} }
func (bl *BeeLogger) writeToLoggers(msg string, level int) { func (bl *BeeLogger) writeToLoggers(when time.Time, msg string, level int) {
for _, l := range bl.outputs { for _, l := range bl.outputs {
err := l.WriteMsg(msg, level) err := l.WriteMsg(when, msg, level)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "unable to WriteMsg to adapter:%v,error:%v\n", l.name, err) fmt.Fprintf(os.Stderr, "unable to WriteMsg to adapter:%v,error:%v\n", l.name, err)
} }
} }
} }
func (bl *BeeLogger) writeMsg(logLevel int, msg string) error { func (bl *BeeLogger) writeMsg(logLevel int, msg string, when time.Time) error {
if bl.enableFuncCallDepth { if bl.enableFuncCallDepth {
_, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth) _, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth)
if !ok { if !ok {
@ -196,9 +198,10 @@ func (bl *BeeLogger) writeMsg(logLevel int, msg string) error {
lm := logMsgPool.Get().(*logMsg) lm := logMsgPool.Get().(*logMsg)
lm.level = logLevel lm.level = logLevel
lm.msg = msg lm.msg = msg
lm.when = when
bl.msgChan <- lm bl.msgChan <- lm
} else { } else {
bl.writeToLoggers(msg, logLevel) bl.writeToLoggers(when, msg, logLevel)
} }
return nil return nil
} }
@ -231,7 +234,7 @@ func (bl *BeeLogger) startLogger() {
for { for {
select { select {
case bm := <-bl.msgChan: case bm := <-bl.msgChan:
bl.writeToLoggers(bm.msg, bm.level) bl.writeToLoggers(bm.when, bm.msg, bm.level)
logMsgPool.Put(bm) logMsgPool.Put(bm)
} }
} }
@ -243,7 +246,7 @@ func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[M] "+format, v...) msg := fmt.Sprintf("[M] "+format, v...)
bl.writeMsg(LevelEmergency, msg) bl.writeMsg(LevelEmergency, msg, time.Now())
} }
// Alert Log ALERT level message. // Alert Log ALERT level message.
@ -252,7 +255,7 @@ func (bl *BeeLogger) Alert(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[A] "+format, v...) msg := fmt.Sprintf("[A] "+format, v...)
bl.writeMsg(LevelAlert, msg) bl.writeMsg(LevelAlert, msg, time.Now())
} }
// Critical Log CRITICAL level message. // Critical Log CRITICAL level message.
@ -261,7 +264,7 @@ func (bl *BeeLogger) Critical(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[C] "+format, v...) msg := fmt.Sprintf("[C] "+format, v...)
bl.writeMsg(LevelCritical, msg) bl.writeMsg(LevelCritical, msg, time.Now())
} }
// Error Log ERROR level message. // Error Log ERROR level message.
@ -270,7 +273,7 @@ func (bl *BeeLogger) Error(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[E] "+format, v...) msg := fmt.Sprintf("[E] "+format, v...)
bl.writeMsg(LevelError, msg) bl.writeMsg(LevelError, msg, time.Now())
} }
// Warning Log WARNING level message. // Warning Log WARNING level message.
@ -279,7 +282,7 @@ func (bl *BeeLogger) Warning(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[W] "+format, v...) msg := fmt.Sprintf("[W] "+format, v...)
bl.writeMsg(LevelWarning, msg) bl.writeMsg(LevelWarning, msg, time.Now())
} }
// Notice Log NOTICE level message. // Notice Log NOTICE level message.
@ -288,7 +291,7 @@ func (bl *BeeLogger) Notice(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[N] "+format, v...) msg := fmt.Sprintf("[N] "+format, v...)
bl.writeMsg(LevelNotice, msg) bl.writeMsg(LevelNotice, msg, time.Now())
} }
// Informational Log INFORMATIONAL level message. // Informational Log INFORMATIONAL level message.
@ -297,7 +300,7 @@ func (bl *BeeLogger) Informational(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[I] "+format, v...) msg := fmt.Sprintf("[I] "+format, v...)
bl.writeMsg(LevelInformational, msg) bl.writeMsg(LevelInformational, msg, time.Now())
} }
// Debug Log DEBUG level message. // Debug Log DEBUG level message.
@ -306,7 +309,7 @@ func (bl *BeeLogger) Debug(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[D] "+format, v...) msg := fmt.Sprintf("[D] "+format, v...)
bl.writeMsg(LevelDebug, msg) bl.writeMsg(LevelDebug, msg, time.Now())
} }
// Warn Log WARN level message. // Warn Log WARN level message.
@ -316,7 +319,7 @@ func (bl *BeeLogger) Warn(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[W] "+format, v...) msg := fmt.Sprintf("[W] "+format, v...)
bl.writeMsg(LevelWarning, msg) bl.writeMsg(LevelWarning, msg, time.Now())
} }
// Info Log INFO level message. // Info Log INFO level message.
@ -326,7 +329,7 @@ func (bl *BeeLogger) Info(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[I] "+format, v...) msg := fmt.Sprintf("[I] "+format, v...)
bl.writeMsg(LevelInformational, msg) bl.writeMsg(LevelInformational, msg, time.Now())
} }
// Trace Log TRACE level message. // Trace Log TRACE level message.
@ -336,7 +339,7 @@ func (bl *BeeLogger) Trace(format string, v ...interface{}) {
return return
} }
msg := fmt.Sprintf("[D] "+format, v...) msg := fmt.Sprintf("[D] "+format, v...)
bl.writeMsg(LevelDebug, msg) bl.writeMsg(LevelDebug, msg, time.Now())
} }
// Flush flush all chan data. // Flush flush all chan data.
@ -351,7 +354,7 @@ func (bl *BeeLogger) Close() {
for { for {
if len(bl.msgChan) > 0 { if len(bl.msgChan) > 0 {
bm := <-bl.msgChan bm := <-bl.msgChan
bl.writeToLoggers(bm.msg, bm.level) bl.writeToLoggers(bm.when, bm.msg, bm.level)
logMsgPool.Put(bm) logMsgPool.Put(bm)
continue continue
} }
@ -362,3 +365,45 @@ func (bl *BeeLogger) Close() {
l.Destroy() l.Destroy()
} }
} }
func formatLogTime(when time.Time) string {
y, mo, d := when.Date()
h, mi, s := when.Clock()
//len(2006/01/02 15:03:04)==19
var buf [20]byte
t := 3
for y >= 10 {
p := y / 10
buf[t] = byte('0' + y - p*10)
y = p
t--
}
buf[0] = byte('0' + y)
buf[4] = '/'
if mo > 9 {
buf[5] = '1'
buf[6] = byte('0' + mo - 9)
} else {
buf[5] = '0'
buf[6] = byte('0' + mo)
}
buf[7] = '/'
t = d / 10
buf[8] = byte('0' + t)
buf[9] = byte('0' + d - t*10)
buf[10] = ' '
t = h / 10
buf[11] = byte('0' + t)
buf[12] = byte('0' + h - t*10)
buf[13] = ':'
t = mi / 10
buf[14] = byte('0' + t)
buf[15] = byte('0' + mi - t*10)
buf[16] = ':'
t = s / 10
buf[17] = byte('0' + t)
buf[18] = byte('0' + s - t*10)
buf[19] = ' '
return string(buf[0:])
}

View File

@ -126,7 +126,7 @@ func (s *SMTPWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAd
// WriteMsg write message in smtp writer. // WriteMsg write message in smtp writer.
// it will send an email with subject and only this message. // it will send an email with subject and only this message.
func (s *SMTPWriter) WriteMsg(msg string, level int) error { func (s *SMTPWriter) WriteMsg(when time.Time, msg string, level int) error {
if level > s.Level { if level > s.Level {
return nil return nil
} }
@ -140,7 +140,7 @@ func (s *SMTPWriter) WriteMsg(msg string, level int) error {
// and send the email all in one step. // and send the email all in one step.
contentType := "Content-Type: text/plain" + "; charset=UTF-8" contentType := "Content-Type: text/plain" + "; charset=UTF-8"
mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress + mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress +
">\r\nSubject: " + s.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) ">\r\nSubject: " + s.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", when.Format("2006-01-02 15:04:05")) + msg)
return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg) return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
} }