add log rotation

This commit is contained in:
ginuerzh
2022-10-20 21:10:25 +08:00
parent 8274b62672
commit b86d7ee06d
3 changed files with 28 additions and 10 deletions

View File

@ -3,6 +3,7 @@ package main
import (
"io"
"os"
"path/filepath"
"github.com/go-gost/core/logger"
"github.com/go-gost/core/service"
@ -12,6 +13,7 @@ import (
xlogger "github.com/go-gost/x/logger"
metrics "github.com/go-gost/x/metrics/service"
"github.com/go-gost/x/registry"
"gopkg.in/natefinch/lumberjack.v2"
)
func buildService(cfg *config.Config) (services []service.Service) {
@ -149,11 +151,23 @@ func logFromConfig(cfg *config.LogConfig) logger.Logger {
case "stderr", "":
out = os.Stderr
default:
f, err := os.OpenFile(cfg.Output, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Warn(err)
if cfg.Rotation != nil {
out = &lumberjack.Logger{
Filename: cfg.Output,
MaxSize: cfg.Rotation.MaxSize,
MaxAge: cfg.Rotation.MaxAge,
MaxBackups: cfg.Rotation.MaxBackups,
LocalTime: cfg.Rotation.LocalTime,
Compress: cfg.Rotation.Compress,
}
} else {
out = f
os.MkdirAll(filepath.Dir(cfg.Output), 0755)
f, err := os.OpenFile(cfg.Output, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Warn(err)
} else {
out = f
}
}
}
opts = append(opts, xlogger.OutputLoggerOption(out))