tstor/log/log.go

51 lines
1.1 KiB
Go
Raw Normal View History

2021-11-18 19:36:07 +00:00
package log
import (
2021-11-20 19:57:25 +00:00
"io"
"os"
"path/filepath"
"github.com/distribyted/distribyted/config"
2021-11-18 19:36:07 +00:00
"github.com/mattn/go-colorable"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
2021-11-20 19:57:25 +00:00
"gopkg.in/natefinch/lumberjack.v2"
2021-11-18 19:36:07 +00:00
)
2021-11-20 19:57:25 +00:00
const FileName = "distribyted.log"
func Load(config *config.Log) {
var writers []io.Writer
2021-11-18 19:36:07 +00:00
// fix console colors on windows
cso := colorable.NewColorableStdout()
2021-11-20 19:57:25 +00:00
writers = append(writers, zerolog.ConsoleWriter{Out: cso})
writers = append(writers, newRollingFile(config))
mw := io.MultiWriter(writers...)
log.Logger = log.Output(mw)
2021-11-18 19:36:07 +00:00
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
2021-11-20 19:57:25 +00:00
l := zerolog.InfoLevel
if config.Debug {
l = zerolog.DebugLevel
}
zerolog.SetGlobalLevel(l)
}
func newRollingFile(config *config.Log) io.Writer {
if err := os.MkdirAll(config.Path, 0744); err != nil {
log.Error().Err(err).Str("path", config.Path).Msg("can't create log directory")
return nil
}
return &lumberjack.Logger{
Filename: filepath.Join(config.Path, FileName),
MaxBackups: config.MaxBackups, // files
MaxSize: config.MaxSize, // megabytes
MaxAge: config.MaxAge, // days
}
2021-11-18 19:36:07 +00:00
}