file.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package log
  2. import (
  3. "context"
  4. "io"
  5. "path/filepath"
  6. "time"
  7. "go-common/library/log/internal/filewriter"
  8. )
  9. // level idx
  10. const (
  11. _infoIdx = iota
  12. _warnIdx
  13. _errorIdx
  14. _totalIdx
  15. )
  16. var _fileNames = map[int]string{
  17. _infoIdx: "info.log",
  18. _warnIdx: "warning.log",
  19. _errorIdx: "error.log",
  20. }
  21. // FileHandler .
  22. type FileHandler struct {
  23. render Render
  24. fws [_totalIdx]*filewriter.FileWriter
  25. }
  26. // NewFile crete a file logger.
  27. func NewFile(dir string, bufferSize, rotateSize int64, maxLogFile int) *FileHandler {
  28. // new info writer
  29. newWriter := func(name string) *filewriter.FileWriter {
  30. var options []filewriter.Option
  31. if rotateSize > 0 {
  32. options = append(options, filewriter.MaxSize(rotateSize))
  33. }
  34. if maxLogFile > 0 {
  35. options = append(options, filewriter.MaxFile(maxLogFile))
  36. }
  37. w, err := filewriter.New(filepath.Join(dir, name), options...)
  38. if err != nil {
  39. panic(err)
  40. }
  41. return w
  42. }
  43. handler := &FileHandler{
  44. render: newPatternRender("[%D %T] [%L] [%S] %M"),
  45. }
  46. for idx, name := range _fileNames {
  47. handler.fws[idx] = newWriter(name)
  48. }
  49. return handler
  50. }
  51. // Log loggint to file .
  52. func (h *FileHandler) Log(ctx context.Context, lv Level, args ...D) {
  53. d := make(map[string]interface{}, 10+len(args))
  54. for _, arg := range args {
  55. d[arg.Key] = arg.Value
  56. }
  57. // add extra fields
  58. addExtraField(ctx, d)
  59. d[_time] = time.Now().Format(_timeFormat)
  60. var w io.Writer
  61. switch lv {
  62. case _warnLevel:
  63. w = h.fws[_warnIdx]
  64. case _errorLevel:
  65. w = h.fws[_errorIdx]
  66. default:
  67. w = h.fws[_infoIdx]
  68. }
  69. h.render.Render(w, d)
  70. w.Write([]byte("\n"))
  71. }
  72. // Close log handler
  73. func (h *FileHandler) Close() error {
  74. for _, fw := range h.fws {
  75. // ignored error
  76. fw.Close()
  77. }
  78. return nil
  79. }
  80. // SetFormat set log format
  81. func (h *FileHandler) SetFormat(format string) {
  82. h.render = newPatternRender(format)
  83. }