stdout.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package log
  2. import (
  3. "context"
  4. "io"
  5. "os"
  6. "time"
  7. )
  8. const defaultPattern = "%L %d-%T %f %M"
  9. var _defaultStdout = NewStdout()
  10. // StdoutHandler stdout log handler
  11. type StdoutHandler struct {
  12. out io.Writer
  13. render Render
  14. }
  15. // NewStdout create a stdout log handler
  16. func NewStdout() *StdoutHandler {
  17. return &StdoutHandler{
  18. out: os.Stderr,
  19. render: newPatternRender(defaultPattern),
  20. }
  21. }
  22. // Log stdout loging, only for developing env.
  23. func (h *StdoutHandler) Log(ctx context.Context, lv Level, args ...D) {
  24. d := make(map[string]interface{}, 10+len(args))
  25. for _, arg := range args {
  26. d[arg.Key] = arg.Value
  27. }
  28. // add extra fields
  29. addExtraField(ctx, d)
  30. d[_time] = time.Now().Format(_timeFormat)
  31. h.render.Render(h.out, d)
  32. h.out.Write([]byte("\n"))
  33. }
  34. // Close stdout loging
  35. func (h *StdoutHandler) Close() error {
  36. return nil
  37. }
  38. // SetFormat set stdout log output format
  39. // %T time format at "15:04:05.999"
  40. // %t time format at "15:04:05"
  41. // %D data format at "2006/01/02"
  42. // %d data format at "01/02"
  43. // %L log level e.g. INFO WARN ERROR
  44. // %f function name and line number e.g. model.Get:121
  45. // %i instance id
  46. // %e deploy env e.g. dev uat fat prod
  47. // %z zone
  48. // %S full file name and line number: /a/b/c/d.go:23
  49. // %s final file name element and line number: d.go:23
  50. // %M log message and additional fields: key=value this is log message
  51. func (h *StdoutHandler) SetFormat(format string) {
  52. h.render = newPatternRender(format)
  53. }