123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- package main
- import (
- "io/ioutil"
- "log"
- "os"
- "path/filepath"
- "time"
- )
- //Zardozlogfile defines the log structure
- type Zardozlogfile struct {
- filename string
- logfile *os.File
- active bool
- }
- //VSlogfile is the logger we use
- var VSlogfile Zardozlogfile
- func init() {
- verbose := os.Getenv("DEBUG")
- log.Println("Verbose mode on: ", verbose)
- DebugLog = (verbose == "true")
- log.Println("DebugLog: ", DebugLog)
- log.Println("Starting Log Engine")
- // just the first time
- var currentFolder = Hpwd()
- os.MkdirAll(filepath.Join(currentFolder, "logs"), 0755)
- //
- VSlogfile.active = DebugLog
- VSlogfile.SetLogFolder()
- go VSlogfile.RotateLogFolder()
- }
- //RotateLogFolder rotates the log folder
- func (lf *Zardozlogfile) RotateLogFolder() {
- for {
- time.Sleep(1 * time.Hour)
- if lf.logfile != nil {
- err := lf.logfile.Close()
- log.Println("[TOOLS][LOG] close logfile returned: ", err)
- }
- lf.SetLogFolder()
- }
- }
- //SetLogFolder sets the log folder
- func (lf *Zardozlogfile) SetLogFolder() {
- if DebugLog {
- lf.EnableLog()
- } else {
- lf.DisableLog()
- }
- if lf.active {
- const layout = "2006-01-02.15"
- orario := time.Now().UTC()
- var currentFolder = Hpwd()
- lf.filename = filepath.Join(currentFolder, "logs", "Zardoz."+orario.Format(layout)+"00.log")
- lf.logfile, _ = os.Create(lf.filename)
- log.Println("[TOOLS][LOG] Logfile is: " + lf.filename)
- log.SetOutput(lf.logfile)
- // log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
- log.SetFlags(log.LstdFlags | log.LUTC)
- } else {
- log.SetOutput(ioutil.Discard)
- }
- }
- //EnableLog enables logging
- func (lf *Zardozlogfile) EnableLog() {
- lf.active = true
- }
- //DisableLog disables logging
- func (lf *Zardozlogfile) DisableLog() {
- lf.active = false
- log.SetFlags(0)
- log.SetOutput(ioutil.Discard)
- }
- //LogEngineStart just triggers the init for the package, and logs it.
- func LogEngineStart() {
- log.Println("LogRotation Init")
- }
- //Hpwd behaves like the unix pwd command, returning the current path
- func Hpwd() string {
- tmpLoc, err := os.Getwd()
- if err != nil {
- tmpLoc = "/tmp"
- log.Printf("[TOOLS][FS] Problem getting unix pwd: %s", err.Error())
- }
- return tmpLoc
- }
|