You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
1.7 KiB
Go
106 lines
1.7 KiB
Go
6 years ago
|
package log
|
||
7 years ago
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
"strconv"
|
||
|
"sync"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
6 years ago
|
/*
|
||
7 years ago
|
var (
|
||
|
fmtBuffer = sync.Pool{
|
||
|
New: func() interface{} {
|
||
|
return new(bytes.Buffer)
|
||
|
},
|
||
|
}
|
||
|
)
|
||
6 years ago
|
*/
|
||
7 years ago
|
|
||
|
// TextFormatter is a text line formatter
|
||
|
type TextFormatter struct {
|
||
|
AppName string
|
||
|
TimeFormat string
|
||
|
|
||
|
init sync.Once
|
||
|
host []byte
|
||
|
app []byte
|
||
|
pid []byte
|
||
|
isterm bool
|
||
|
}
|
||
|
|
||
6 years ago
|
// Format implements Formatter
|
||
|
func (f *TextFormatter) Format(level Level, msg string, logger *Logger) []byte {
|
||
7 years ago
|
// output format: DATE LEVEL HOST APP PID file:line message
|
||
|
// 2001-10-10T12:00:00,000+0800 INFO web-1 app 1234 main/main.go:1234 message ...
|
||
|
|
||
|
f.init.Do(func() {
|
||
|
if f.AppName == "" {
|
||
|
f.AppName = filepath.Base(os.Args[0])
|
||
|
}
|
||
|
f.app = []byte(f.AppName)
|
||
|
|
||
|
if f.TimeFormat == "" {
|
||
|
f.TimeFormat = "2006-01-02T15:04:05.000-0700"
|
||
|
}
|
||
|
|
||
|
f.isterm = IsTerminal(logger.Out)
|
||
|
|
||
7 years ago
|
host, _ := os.Hostname()
|
||
7 years ago
|
f.host = []byte(host)
|
||
|
|
||
|
f.pid = []byte(strconv.Itoa(os.Getpid()))
|
||
|
})
|
||
|
|
||
6 years ago
|
//buf := fmtBuffer.Get().(*bytes.Buffer)
|
||
|
//buf.Reset()
|
||
|
//defer fmtBuffer.Put(buf)
|
||
|
buf := new(bytes.Buffer)
|
||
7 years ago
|
|
||
|
// timestamp
|
||
|
timeStr := time.Now().Format(f.TimeFormat)
|
||
|
buf.WriteString(timeStr)
|
||
|
|
||
7 years ago
|
/*
|
||
|
// host
|
||
|
buf.WriteByte(' ')
|
||
|
buf.Write(f.host)
|
||
7 years ago
|
|
||
7 years ago
|
// name
|
||
|
buf.WriteByte(' ')
|
||
|
buf.Write(f.app)
|
||
7 years ago
|
|
||
7 years ago
|
// pid
|
||
|
buf.WriteByte(' ')
|
||
|
buf.Write(f.pid)
|
||
|
*/
|
||
7 years ago
|
|
||
|
// file, line
|
||
7 years ago
|
file, line := FilelineCaller(4)
|
||
7 years ago
|
buf.WriteString(" [")
|
||
7 years ago
|
buf.WriteString(file)
|
||
|
buf.WriteByte(':')
|
||
|
buf.WriteString(strconv.Itoa(line))
|
||
7 years ago
|
buf.WriteString("]")
|
||
7 years ago
|
|
||
7 years ago
|
// level
|
||
7 years ago
|
buf.WriteByte(' ')
|
||
7 years ago
|
if f.isterm {
|
||
|
buf.WriteString(level.ColorString())
|
||
|
} else {
|
||
|
buf.WriteString(level.String())
|
||
|
}
|
||
|
// msg
|
||
|
buf.WriteString(": ")
|
||
7 years ago
|
buf.WriteString(msg)
|
||
|
|
||
|
// newline
|
||
7 years ago
|
if msg[len(msg)-1] != '\n' {
|
||
|
buf.WriteByte('\n')
|
||
|
}
|
||
7 years ago
|
|
||
|
return buf.Bytes()
|
||
|
}
|