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.

105 lines
1.7 KiB
Go

7 years ago
package formatters
import (
"bytes"
"os"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/fangdingjun/go-log"
7 years ago
)
var (
fmtBuffer = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
)
// TextFormatter is a text line formatter
type TextFormatter struct {
AppName string
TimeFormat string
init sync.Once
host []byte
app []byte
pid []byte
isterm bool
}
// Format implements log.Formatter
func (f *TextFormatter) Format(level log.Level, msg string, logger *log.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)
host, _ := os.Hostname()
7 years ago
f.host = []byte(host)
f.pid = []byte(strconv.Itoa(os.Getpid()))
})
buf := fmtBuffer.Get().(*bytes.Buffer)
buf.Reset()
defer fmtBuffer.Put(buf)
// timestamp
timeStr := time.Now().Format(f.TimeFormat)
buf.WriteString(timeStr)
/*
// host
buf.WriteByte(' ')
buf.Write(f.host)
7 years ago
// name
buf.WriteByte(' ')
buf.Write(f.app)
7 years ago
// pid
buf.WriteByte(' ')
buf.Write(f.pid)
*/
7 years ago
// file, line
file, line := FilelineCaller(4)
buf.WriteString(" [")
7 years ago
buf.WriteString(file)
buf.WriteByte(':')
buf.WriteString(strconv.Itoa(line))
buf.WriteString("]")
7 years ago
// level
buf.WriteByte(' ')
if f.isterm {
buf.WriteString(level.ColorString())
} else {
buf.WriteString(level.String())
}
// msg
buf.WriteString(": ")
7 years ago
buf.WriteString(msg)
// newline
if msg[len(msg)-1] != '\n' {
buf.WriteByte('\n')
}
7 years ago
return buf.Bytes()
}