file.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package log
  2. import (
  3. "fmt"
  4. stdlog "log"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. )
  9. const (
  10. dailyRolling = "2006-01-02"
  11. )
  12. type fileHandler struct {
  13. l *stdlog.Logger
  14. f *os.File
  15. basePath string
  16. filePath string
  17. fileFrag string
  18. }
  19. func NewFileHandler(basePath string) Handler {
  20. if _, file := filepath.Split(basePath); file == "" {
  21. panic("invalid base path")
  22. }
  23. l := stdlog.New(nil, "", stdlog.LstdFlags|stdlog.Lshortfile)
  24. f := &fileHandler{l: l, basePath: basePath}
  25. if err := f.roll(); err != nil {
  26. panic(err)
  27. }
  28. return f
  29. }
  30. func (r *fileHandler) Log(level, msg string) {
  31. _ = r.roll()
  32. _ = r.l.Output(5, fmt.Sprintf("[%s] %s", level, msg))
  33. }
  34. func (r *fileHandler) Close() error {
  35. if r.f != nil {
  36. return r.f.Close()
  37. }
  38. return nil
  39. }
  40. func (r *fileHandler) roll() error {
  41. suffix := time.Now().Format(dailyRolling)
  42. if r.f != nil {
  43. if suffix == r.fileFrag {
  44. return nil
  45. }
  46. r.f.Close()
  47. r.f = nil
  48. }
  49. r.fileFrag = suffix
  50. r.filePath = fmt.Sprintf("%s.%s", r.basePath, r.fileFrag)
  51. if dir, _ := filepath.Split(r.basePath); dir != "" && dir != "." {
  52. if err := os.MkdirAll(dir, 0777); err != nil {
  53. return err
  54. }
  55. }
  56. f, err := os.OpenFile(r.filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  57. if err != nil {
  58. return err
  59. }
  60. r.f = f
  61. r.l.SetOutput(f)
  62. return nil
  63. }