filelog.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package mlog
  2. import (
  3. "log"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "strconv"
  8. "time"
  9. )
  10. // Filelog represents an active object that logs on file to record error or other useful info.
  11. // The filelog info is output to os.Stderr.
  12. // The loginst is an point of logger in Std-Packages.
  13. // The isopen is a label represents whether open filelog or not.
  14. type filelog struct {
  15. plog
  16. loginst *log.Logger
  17. }
  18. var flog *filelog
  19. // LogInst get the singleton filelog object.
  20. func LogInst() *filelog {
  21. if flog == nil {
  22. InitFilelog(false, "")
  23. }
  24. return flog
  25. }
  26. // The InitFilelog is init the flog.
  27. func InitFilelog(isopen bool, fp string) {
  28. if !isopen {
  29. flog = &filelog{}
  30. flog.loginst = nil
  31. flog.isopen = isopen
  32. return
  33. }
  34. if fp == "" {
  35. wd := os.Getenv("GOPATH")
  36. if wd == "" {
  37. //panic("GOPATH is not setted in env.")
  38. file, _ := exec.LookPath(os.Args[0])
  39. path := filepath.Dir(file)
  40. wd = path
  41. }
  42. if wd == "" {
  43. panic("GOPATH is not setted in env or can not get exe path.")
  44. }
  45. fp = wd + "/log/"
  46. }
  47. flog = newFilelog(isopen, fp)
  48. }
  49. // The newFilelog returns initialized filelog object.
  50. // The default file path is "WORKDIR/log/log.2011-01-01".
  51. func newFilelog(isopen bool, logpath string) *filelog {
  52. year, month, day := time.Now().Date()
  53. filename := "log." + strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
  54. err := os.MkdirAll(logpath, 0755)
  55. if err != nil {
  56. panic("logpath error : " + logpath + "\n")
  57. }
  58. f, err := os.OpenFile(logpath+"/"+filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  59. if err != nil {
  60. panic("log file open error : " + logpath + "/" + filename + "\n")
  61. }
  62. pfilelog := &filelog{}
  63. pfilelog.loginst = log.New(f, "", log.LstdFlags)
  64. pfilelog.isopen = isopen
  65. return pfilelog
  66. }
  67. func (this *filelog) log(lable string, str string) {
  68. if !this.isopen {
  69. return
  70. }
  71. file, line := this.getCaller()
  72. this.loginst.Printf("%s:%d: %s %s\n", file, line, lable, str)
  73. }
  74. // LogError logs error info.
  75. func (this *filelog) LogError(str string) {
  76. this.log("[ERROR]", str)
  77. }
  78. // LogError logs normal info.
  79. func (this *filelog) LogInfo(str string) {
  80. this.log("[INFO]", str)
  81. }