diff --git a/README.md b/README.md index 3dcb4ef..66bdb32 100644 --- a/README.md +++ b/README.md @@ -200,8 +200,8 @@ freq_alert = false # 日志配置 [logging] - # 开启日志记录 - enable = false + # 开启日志记录(程序异常时会记录关键信息,不建议关闭) + enable = true # 默认值:Linux/MacOS为/tmp/kd_.log,windows为%TMPDIR%/kd_.log path = "" # 日志级别,支持:DEBUG/INFO/WARN/PANIC/FATAL diff --git a/cmd/kd.go b/cmd/kd.go index 400ae3b..eef6a3b 100644 --- a/cmd/kd.go +++ b/cmd/kd.go @@ -121,8 +121,7 @@ func flagUpdate(ctx *cli.Context, _ bool) (err error) { if doUpdate { // emoji.Println(":lightning: Let's update now") - err = daemon.KillDaemonIfRunning() - if err != nil { + if err = daemon.KillDaemonIfRunning(); err != nil { warnMsg := "可能会影响后续文件替换。如果出现问题,请手动执行`kd --stop`后重试" d.EchoWarn("停止守护进程出现异常(%s),%s", err, warnMsg) if p, perr := daemon.FindServerProcess(); perr == nil { @@ -272,7 +271,14 @@ func main() { if err != nil { d.EchoFatal(err.Error()) } - defer l.Sync() + defer func() { + if r := recover(); r != nil { + zap.S().Errorln("Application crashed", zap.Any("reason", r)) + if syncErr := l.Sync(); syncErr != nil { + fmt.Printf("Failed to sync logger: %v\n", syncErr) + } + } + }() } zap.S().Debugf("Got configuration: %+v", cfg) zap.S().Debugf("Got run info: %+v", run.Info) diff --git a/config/config.go b/config/config.go index 2855289..ce2ce97 100644 --- a/config/config.go +++ b/config/config.go @@ -22,7 +22,7 @@ var CONFIG_PATH string type LoggerConfig struct { Enable bool `default:"true" toml:"enable"` Path string `toml:"path"` - Level string `default:"info" toml:"level"` + Level string `default:"warn" toml:"level"` Stderr bool `default:"false" toml:"stderr"` RedirectToStream bool `default:"false" toml:"redirect_to_stream"` } diff --git a/logger/logger.go b/logger/logger.go index 82688df..21a3795 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -2,6 +2,7 @@ package logger import ( "fmt" + "log" "os" "os/user" "path/filepath" @@ -22,8 +23,7 @@ func buildLogger(logCfg *config.LoggerConfig, options ...zap.Option) (*zap.Logge } else { var f string if logCfg.Path == "" { - u, err := user.Current() - if err != nil { + if u, err := user.Current(); err != nil { f = filepath.Join(os.TempDir(), "kd.log") } else { name := strings.ReplaceAll(u.Username, " ", "_") @@ -52,10 +52,9 @@ func buildLogger(logCfg *config.LoggerConfig, options ...zap.Option) (*zap.Logge func InitLogger(logCfg *config.LoggerConfig) (*zap.Logger, error) { l, err := buildLogger(logCfg) if err != nil { - panic(err) + log.Panicln(err) } zap.ReplaceGlobals(l) - return l, err }