2018-06-06 15:30:23 +09:00
|
|
|
package rotater
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2018-06-12 22:50:41 +09:00
|
|
|
"path/filepath"
|
2018-06-06 15:30:23 +09:00
|
|
|
"log"
|
|
|
|
"amuz.es/src/infra/goutils/logger"
|
2018-06-12 21:54:31 +09:00
|
|
|
"github.com/lestrrat-go/file-rotatelogs"
|
2018-06-06 15:30:23 +09:00
|
|
|
)
|
|
|
|
|
2018-06-10 16:57:59 +09:00
|
|
|
var loggers RotateSyncerSet
|
2018-06-06 15:30:23 +09:00
|
|
|
|
2018-06-12 08:45:20 +09:00
|
|
|
func NewLogWriter(FileName string, logDir string, options ...Option) (logger.RotateSyncer, error) {
|
2018-06-06 15:30:23 +09:00
|
|
|
switch FileName {
|
|
|
|
case "Stdout":
|
2018-06-12 08:45:20 +09:00
|
|
|
return NewLocked(os.Stdout), nil
|
2018-06-06 15:30:23 +09:00
|
|
|
case "Stderr":
|
2018-06-12 08:45:20 +09:00
|
|
|
return NewLocked(os.Stderr), nil
|
2018-06-06 15:30:23 +09:00
|
|
|
default:
|
|
|
|
logpath := FileName
|
|
|
|
if logDir != "" {
|
2018-06-12 22:50:41 +09:00
|
|
|
logpath = filepath.Join(logDir, FileName)
|
2018-06-06 15:30:23 +09:00
|
|
|
}
|
2018-06-12 22:50:41 +09:00
|
|
|
logpath,_ = filepath.Abs(logpath)
|
2018-06-06 15:30:23 +09:00
|
|
|
log.Println(" Attention!! log writes to ", logpath)
|
2018-06-12 21:54:31 +09:00
|
|
|
options=append(options,rotatelogs.WithLinkName(logpath))
|
2018-06-12 22:50:41 +09:00
|
|
|
if logWriter, err := NewRotater(logpath+".%Y%m%d", options...); err != nil {
|
2018-06-12 08:45:20 +09:00
|
|
|
return nil, err
|
|
|
|
} else {
|
|
|
|
loggers.Store(logWriter)
|
|
|
|
logWriter.SetOnClose(func() { loggers.Delete(logWriter) })
|
|
|
|
return logWriter, nil
|
|
|
|
}
|
2018-06-06 15:30:23 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Rotate() {
|
|
|
|
loggers.Range(func(rotater logger.RotateSyncer) {
|
|
|
|
rotater.Sync()
|
|
|
|
rotater.Rotate()
|
|
|
|
})
|
|
|
|
log.Println("rotated")
|
|
|
|
}
|
|
|
|
|
|
|
|
func Close() {
|
|
|
|
loggers.Range(func(rotater logger.RotateSyncer) {
|
|
|
|
rotater.Sync()
|
|
|
|
rotater.Close()
|
|
|
|
})
|
|
|
|
log.Println("end of log")
|
|
|
|
}
|