log.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package log
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "runtime"
  10. "sync"
  11. "time"
  12. "strconv"
  13. "github.com/mattn/go-colorable"
  14. "github.com/mattn/go-isatty"
  15. "github.com/valyala/fasttemplate"
  16. "github.com/labstack/gommon/color"
  17. )
  18. type (
  19. Logger struct {
  20. prefix string
  21. level uint8
  22. output io.Writer
  23. template *fasttemplate.Template
  24. levels []string
  25. color *color.Color
  26. bufferPool sync.Pool
  27. mutex sync.Mutex
  28. }
  29. Fields map[string]interface{}
  30. )
  31. const (
  32. DEBUG = iota
  33. INFO
  34. WARN
  35. ERROR
  36. FATAL
  37. OFF
  38. )
  39. var (
  40. global = New("-")
  41. defaultFormat = `{"time":"${time_rfc3339}","level":"${level}","prefix":"${prefix}",` +
  42. `"file":"${short_file}","line":"${line}","message":"${message}"}` + "\n"
  43. )
  44. func New(prefix string) (l *Logger) {
  45. l = &Logger{
  46. level: INFO,
  47. prefix: prefix,
  48. template: l.newTemplate(defaultFormat),
  49. color: color.New(),
  50. bufferPool: sync.Pool{
  51. New: func() interface{} {
  52. return bytes.NewBuffer(make([]byte, 256))
  53. },
  54. },
  55. }
  56. l.initLevels()
  57. l.SetOutput(colorable.NewColorableStdout())
  58. return
  59. }
  60. func (l *Logger) initLevels() {
  61. l.levels = []string{
  62. l.color.Blue("DEBUG"),
  63. l.color.Green("INFO"),
  64. l.color.Yellow("WARN"),
  65. l.color.Red("ERROR"),
  66. l.color.RedBg("FATAL"),
  67. }
  68. }
  69. func (l *Logger) newTemplate(format string) *fasttemplate.Template {
  70. return fasttemplate.New(format, "${", "}")
  71. }
  72. func (l *Logger) DisableColor() {
  73. l.color.Disable()
  74. l.initLevels()
  75. }
  76. func (l *Logger) EnableColor() {
  77. l.color.Enable()
  78. l.initLevels()
  79. }
  80. func (l *Logger) Prefix() string {
  81. return l.prefix
  82. }
  83. func (l *Logger) SetPrefix(p string) {
  84. l.prefix = p
  85. }
  86. func (l *Logger) Level() uint8 {
  87. return l.level
  88. }
  89. func (l *Logger) SetLevel(v uint8) {
  90. l.level = v
  91. }
  92. func (l *Logger) Output() io.Writer {
  93. return l.output
  94. }
  95. func (l *Logger) SetFormat(f string) {
  96. l.template = l.newTemplate(f)
  97. }
  98. func (l *Logger) SetOutput(w io.Writer) {
  99. l.output = w
  100. if w, ok := w.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) {
  101. l.DisableColor()
  102. }
  103. }
  104. func (l *Logger) Print(i ...interface{}) {
  105. fmt.Fprintln(l.output, i...)
  106. }
  107. func (l *Logger) Printf(format string, args ...interface{}) {
  108. f := fmt.Sprintf("%s\n", format)
  109. fmt.Fprintf(l.output, f, args...)
  110. }
  111. func (l *Logger) Debug(i ...interface{}) {
  112. l.log(DEBUG, "", i...)
  113. }
  114. func (l *Logger) Debugf(format string, args ...interface{}) {
  115. l.log(DEBUG, format, args...)
  116. }
  117. func (l *Logger) Info(i ...interface{}) {
  118. l.log(INFO, "", i...)
  119. }
  120. func (l *Logger) Infof(format string, args ...interface{}) {
  121. l.log(INFO, format, args...)
  122. }
  123. func (l *Logger) Warn(i ...interface{}) {
  124. l.log(WARN, "", i...)
  125. }
  126. func (l *Logger) Warnf(format string, args ...interface{}) {
  127. l.log(WARN, format, args...)
  128. }
  129. func (l *Logger) Error(i ...interface{}) {
  130. l.log(ERROR, "", i...)
  131. }
  132. func (l *Logger) Errorf(format string, args ...interface{}) {
  133. l.log(ERROR, format, args...)
  134. }
  135. func (l *Logger) Fatal(i ...interface{}) {
  136. l.log(FATAL, "", i...)
  137. os.Exit(1)
  138. }
  139. func (l *Logger) Fatalf(format string, args ...interface{}) {
  140. l.log(FATAL, format, args...)
  141. os.Exit(1)
  142. }
  143. func DisableColor() {
  144. global.DisableColor()
  145. }
  146. func EnableColor() {
  147. global.EnableColor()
  148. }
  149. func Prefix() string {
  150. return global.Prefix()
  151. }
  152. func SetPrefix(p string) {
  153. global.SetPrefix(p)
  154. }
  155. func Level() uint8 {
  156. return global.Level()
  157. }
  158. func SetLevel(v uint8) {
  159. global.SetLevel(v)
  160. }
  161. func Output() io.Writer {
  162. return global.Output()
  163. }
  164. func SetOutput(w io.Writer) {
  165. global.SetOutput(w)
  166. }
  167. func SetFormat(f string) {
  168. global.SetFormat(f)
  169. }
  170. func Print(i ...interface{}) {
  171. global.Print(i...)
  172. }
  173. func Printf(format string, args ...interface{}) {
  174. global.Printf(format, args...)
  175. }
  176. func Debug(i ...interface{}) {
  177. global.Debug(i...)
  178. }
  179. func Debugf(format string, args ...interface{}) {
  180. global.Debugf(format, args...)
  181. }
  182. func Info(i ...interface{}) {
  183. global.Info(i...)
  184. }
  185. func Infof(format string, args ...interface{}) {
  186. global.Infof(format, args...)
  187. }
  188. func Warn(i ...interface{}) {
  189. global.Warn(i...)
  190. }
  191. func Warnf(format string, args ...interface{}) {
  192. global.Warnf(format, args...)
  193. }
  194. func Error(i ...interface{}) {
  195. global.Error(i...)
  196. }
  197. func Errorf(format string, args ...interface{}) {
  198. global.Errorf(format, args...)
  199. }
  200. func Fatal(i ...interface{}) {
  201. global.Fatal(i...)
  202. }
  203. func Fatalf(format string, args ...interface{}) {
  204. global.Fatalf(format, args...)
  205. }
  206. func (l *Logger) log(v uint8, format string, args ...interface{}) {
  207. l.mutex.Lock()
  208. defer l.mutex.Unlock()
  209. buf := l.bufferPool.Get().(*bytes.Buffer)
  210. buf.Reset()
  211. defer l.bufferPool.Put(buf)
  212. _, file, line, _ := runtime.Caller(3)
  213. if v >= l.level {
  214. message := ""
  215. if format == "" {
  216. message = fmt.Sprint(args...)
  217. } else {
  218. message = fmt.Sprintf(format, args...)
  219. }
  220. if v == FATAL {
  221. stack := make([]byte, 4<<10)
  222. length := runtime.Stack(stack, true)
  223. message = message + "\n" + string(stack[:length])
  224. }
  225. _, err := l.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) {
  226. switch tag {
  227. case "time_rfc3339":
  228. return w.Write([]byte(time.Now().Format(time.RFC3339)))
  229. case "level":
  230. return w.Write([]byte(l.levels[v]))
  231. case "prefix":
  232. return w.Write([]byte(l.prefix))
  233. case "long_file":
  234. return w.Write([]byte(file))
  235. case "short_file":
  236. return w.Write([]byte(path.Base(file)))
  237. case "line":
  238. return w.Write([]byte(strconv.Itoa(line)))
  239. case "message":
  240. return w.Write([]byte(message))
  241. default:
  242. return w.Write([]byte(fmt.Sprintf("[unknown tag %s]", tag)))
  243. }
  244. })
  245. if err == nil {
  246. l.output.Write(buf.Bytes())
  247. }
  248. }
  249. }
  250. func JSON(f Fields) string {
  251. s, err := json.Marshal(f)
  252. if err != nil {
  253. panic(err)
  254. }
  255. return string(s)
  256. }