// main.go package main import ( "log" "time" ) const logFileName = "libo" func init() { log.Println("init log ...") setupLog() //time.Sleep(3 * time.Second) log.Println("this is output ...") } func main() { log.Println("- - - - - - - - - - - - - - -") log.Println("daemon started") go worker() time.Sleep(3 * time.Second) stop <- struct{}{} log.Println("daemon terminated") } func setupLog() { log.SetPrefix("[log] ") log.SetFlags(log.Lshortfile | log.LstdFlags) lf, err := NewLogFile(logFileName, nil) if err != nil { log.Fatal("Unable to create log file: ", err) } log.SetOutput(lf) // rotate log every 30 seconds. rotateLogSignal := time.Tick(2 * time.Second) go func() { for { <-rotateLogSignal if err := lf.Rotate(); err != nil { log.Fatal("Unable to rotate log: ", err) } } }() } var ( stop = make(chan struct{}) ) func worker() { for { // spam to log every one second (as payload). log.Print("+ ", time.Now().Unix()) time.Sleep(time.Second) select { case <-stop: return default: } } }
說明this
一個簡單的 go 日誌輪播功能,沒有特別的之處,主要是配合 channel/log/timer 實現日誌自動備份spa