log.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. package main
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. )
  9. //Zardozlogfile defines the log structure
  10. type Zardozlogfile struct {
  11. filename string
  12. logfile *os.File
  13. active bool
  14. }
  15. //VSlogfile is the logger we use
  16. var VSlogfile Zardozlogfile
  17. func init() {
  18. verbose := os.Getenv("DEBUG")
  19. log.Println("Verbose mode on: ", verbose)
  20. DebugLog = (verbose == "true")
  21. log.Println("DebugLog: ", DebugLog)
  22. log.Println("Starting Log Engine")
  23. // just the first time
  24. var currentFolder = Hpwd()
  25. os.MkdirAll(filepath.Join(currentFolder, "logs"), 0755)
  26. //
  27. VSlogfile.active = DebugLog
  28. VSlogfile.SetLogFolder()
  29. go VSlogfile.RotateLogFolder()
  30. }
  31. //RotateLogFolder rotates the log folder
  32. func (lf *Zardozlogfile) RotateLogFolder() {
  33. for {
  34. time.Sleep(1 * time.Hour)
  35. if lf.logfile != nil {
  36. err := lf.logfile.Close()
  37. log.Println("[TOOLS][LOG] close logfile returned: ", err)
  38. }
  39. lf.SetLogFolder()
  40. }
  41. }
  42. //SetLogFolder sets the log folder
  43. func (lf *Zardozlogfile) SetLogFolder() {
  44. if DebugLog {
  45. lf.EnableLog()
  46. } else {
  47. lf.DisableLog()
  48. }
  49. if lf.active {
  50. const layout = "2006-01-02.15"
  51. orario := time.Now().UTC()
  52. var currentFolder = Hpwd()
  53. lf.filename = filepath.Join(currentFolder, "logs", "Zardoz."+orario.Format(layout)+"00.log")
  54. lf.logfile, _ = os.Create(lf.filename)
  55. log.Println("[TOOLS][LOG] Logfile is: " + lf.filename)
  56. log.SetOutput(lf.logfile)
  57. // log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
  58. log.SetFlags(log.LstdFlags | log.LUTC)
  59. } else {
  60. log.SetOutput(ioutil.Discard)
  61. }
  62. }
  63. //EnableLog enables logging
  64. func (lf *Zardozlogfile) EnableLog() {
  65. lf.active = true
  66. }
  67. //DisableLog disables logging
  68. func (lf *Zardozlogfile) DisableLog() {
  69. lf.active = false
  70. log.SetFlags(0)
  71. log.SetOutput(ioutil.Discard)
  72. }
  73. //LogEngineStart just triggers the init for the package, and logs it.
  74. func LogEngineStart() {
  75. log.Println("LogRotation Init")
  76. }
  77. //Hpwd behaves like the unix pwd command, returning the current path
  78. func Hpwd() string {
  79. tmpLoc, err := os.Getwd()
  80. if err != nil {
  81. tmpLoc = "/tmp"
  82. log.Printf("[TOOLS][FS] Problem getting unix pwd: %s", err.Error())
  83. }
  84. return tmpLoc
  85. }