3 Commits

Author SHA1 Message Date
frank 25a9f43c1a rotation 2 years ago
frank c7cc9fe243 rotation 2 years ago
ldf 66ee74ffbe allow default logger 3 years ago
  1. 53
      auto_rotate.go
  2. 0
      cmd/logs/cmd.error
  3. 14
      cmd/print.go
  4. 17
      config.go
  5. 135
      logger.go

53
auto_rotate.go

@ -0,0 +1,53 @@
package log
import (
"fmt"
"github.com/robfig/cron"
"log"
"sync"
"time"
)
var (
logPath string
once sync.Once
Spec = "@daily"
)
// RegisterRotationWithSpec set up crontab scheduler for log rotation
//
// spec, "* * * * * *"; "@daily"
func RegisterRotationWithSpec(path, spec string) {
if "" == spec {
spec = Spec
}
listening(path, spec)
}
func RegisterRotation(path string) {
listening(path, Spec)
}
func listening(path, spec string) {
once.Do(func() {
logPath = path
rotate()
go _listening(spec)
})
}
func _listening(spec string) {
_c := cron.New()
if err := _c.AddFunc(spec, rotate); nil != err {
panic(fmt.Sprintf("failed to establish crontab job: %s", err.Error()))
} else {
log.Println("log rotation started ...")
}
_c.Start()
select {}
}
func rotate() {
RotateLogger(New(logPath+time.Now().Format("2006-01-02"), logPath))
}

0
cmd/logs/cmd.error

14
cmd/print.go

@ -1,11 +1,13 @@
package main
import "git.drinkme.beer/yinghe/log"
import (
"git.drinkme.beer/yinghe/log"
)
func main() {
log.Infof("hahah")
log.ReloadLogger("./conf/cfg.toml")
log.Infof(" reloaded.")
return
spec := "@daily"
log.RegisterRotationWithSpec(`./logs/cmd`, spec)
log.RegisterRotation("./log/cmd")
log.Infof("ping")
log.Infof("pong")
}

17
config.go

@ -1,9 +1,11 @@
package log
type LogCfg struct {
LogConf string `toml:"conf"`
LogPath string `toml:"path"`
APPName string `toml:"app_name"`
LogConf string `toml:"conf"`
LogPath string `toml:"path"`
LogInfoPath string `toml:"path_info"`
LogErrPath string `toml:"path_err"`
APPName string `toml:"app_name"`
DInfo string
DError string
@ -15,9 +17,14 @@ type GlobalCfg struct {
Logs LogCfg `toml:"logger"`
}
var cfg LogCfg
const (
// ConfigFile is the default configuration file name.
ConfigFile = "./conf/cfg.toml"
)
func New(infoPath, errPath string) LogCfg {
return LogCfg{
LogInfoPath: infoPath,
LogErrPath: errPath,
}
}

135
logger.go

@ -1,10 +1,14 @@
package log
import (
"errors"
"fmt"
"io/fs"
"io/ioutil"
"log"
"os"
"path"
"time"
"github.com/BurntSushi/toml"
"go.uber.org/zap"
@ -14,8 +18,6 @@ import (
var (
logger Logger
//OutputPaths = ""
//ErrOutputPaths = ""
)
type YLogger struct {
@ -37,28 +39,35 @@ type Logger interface {
func init() {
var (
logCfg GlobalCfg
cfg LogCfg
logCfg GlobalCfg
)
log.Println("config file name -->", ConfigFile)
log.Println("starting ...")
if _, err := toml.DecodeFile(ConfigFile, &logCfg); err != nil {
log.Fatalf("Read config file err:%s", err.Error())
//log.Fatalf("Read config file err:%s", err.Error())
log.Println("failed to open config file")
if err = InitLog("", cfg); nil != err {
log.Println(err.Error())
}
return
}
cfg = logCfg.Logs
cfg.OutputPaths = cfg.LogPath + cfg.APPName + ".log"
cfg.OutputPaths = cfg.LogPath + cfg.APPName + time.Now().Format("2006-01-02") + ".log"
cfg.ErrorOutputPaths = cfg.LogPath + cfg.APPName + ".error"
err := InitLog(cfg.LogConf)
err := InitLog(cfg.LogConf, cfg)
if err != nil {
log.Printf("[InitLog] warn: %v", err)
}
}
func ReloadLogger(configFile string) {
var (
logCfg GlobalCfg
cfg LogCfg
logCfg GlobalCfg
)
log.Println("config file name -->", configFile)
@ -66,44 +75,110 @@ func ReloadLogger(configFile string) {
log.Fatalf("Read config file err:%s", err.Error())
}
cfg = logCfg.Logs
cfg.OutputPaths = cfg.LogPath + cfg.APPName + ".log"
cfg.OutputPaths = cfg.LogPath + cfg.APPName + time.Now().Format("2006-01-02") + ".log"
cfg.ErrorOutputPaths = cfg.LogPath + cfg.APPName + ".error"
err := InitLog(cfg.LogConf)
err := InitLog(cfg.LogConf, cfg)
if err != nil {
log.Printf("[ReloadLogger] warn: %v", err)
}
}
func InitLog(logConfFile string) error {
if logConfFile == "" {
InitLogger(nil)
return fmt.Errorf("log configure file name is nil")
}
if path.Ext(logConfFile) != ".yml" {
InitLogger(nil)
return fmt.Errorf("log configure file name{%s} suffix must be .yml", logConfFile)
func RotateLogger(cfg LogCfg) {
cfg.OutputPaths = cfg.LogInfoPath + cfg.APPName + ".log"
cfg.ErrorOutputPaths = cfg.LogErrPath + cfg.APPName + ".error"
if _, err := os.Stat(cfg.OutputPaths); errors.Is(err, fs.ErrNotExist) {
if _, err = os.Create(cfg.OutputPaths); nil != err {
log.Printf("[RotateLogger] error: %s", err.Error())
return
}
}
confFileStream, err := ioutil.ReadFile(logConfFile)
//if _, err := os.Stat(cfg.ErrorOutputPaths); errors.Is(err, fs.ErrNotExist) {
// if _, err = os.Create(cfg.ErrorOutputPaths); nil != err {
// log.Printf("[RotateLogger] error: %s", err.Error())
// return
// }
//}
err := InitLog(cfg.LogConf, cfg)
if err != nil {
InitLogger(nil)
return fmt.Errorf("ioutil.ReadFile(file:%s) = error:%v", logConfFile, err)
log.Printf("[RotateLogger] warn: %v", err)
}
}
var defaultZapConfig = []byte(`
level: "info"
development: false
disableCaller: false
disableStacktrace: false
sampling:
encoding: "console"
# encoder
encoderConfig:
messageKey: "message"
levelKey: "level"
timeKey: "time"
nameKey: "logger"
callerKey: "caller"
stacktraceKey: "stacktrace"
lineEnding: ""
# levelEncoder: "capitalColor"
timeEncoder: "iso8601"
durationEncoder: "seconds"
callerEncoder: "short"
nameEncoder: ""
`)
func InitLog(logConfFile string, cfg LogCfg) error {
conf := &zap.Config{}
err = yaml.Unmarshal(confFileStream, conf)
if err != nil {
InitLogger(nil)
return fmt.Errorf("[Unmarshal]init logger error: %v", err)
}
if logConfFile != "" {
if path.Ext(logConfFile) != ".yml" {
InitLogger(nil)
return fmt.Errorf("log configure file name{%s} suffix must be .yml", logConfFile)
}
log.Println("to set yuanex logger ...")
confFileStream, err := ioutil.ReadFile(logConfFile)
if err != nil {
InitLogger(nil)
return fmt.Errorf("ioutil.ReadFile(file:%s) = error:%v", logConfFile, err)
}
err = yaml.Unmarshal(confFileStream, conf)
if err != nil {
InitLogger(nil)
return fmt.Errorf("[Unmarshal]init logger error: %v", err)
}
} else {
conf = &zap.Config{
Level: zap.NewAtomicLevel(),
Development: false,
DisableCaller: false,
DisableStacktrace: false,
Sampling: nil,
Encoding: "console",
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "time",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: "stacktrace",
EncodeTime: zapcore.EpochMillisTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeName: nil,
EncodeLevel: nil,
},
}
err := yaml.Unmarshal(defaultZapConfig, conf)
if err != nil {
InitLogger(nil)
return fmt.Errorf("[Unmarshal]init logger error: %v", err)
}
}
conf.OutputPaths = append(conf.OutputPaths, cfg.OutputPaths)
conf.ErrorOutputPaths = append(conf.ErrorOutputPaths, cfg.ErrorOutputPaths)
log.Println("ErrorOutputPahts -->", conf.ErrorOutputPaths)
InitLogger(conf)
return nil

Loading…
Cancel
Save