Skip to content

Commit

Permalink
Fix panicking on logger init
Browse files Browse the repository at this point in the history
  • Loading branch information
mumoshu committed Nov 24, 2023
1 parent 0e9cd8a commit f3d0374
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,10 @@ func main() {
rootCmd.AddCommand(cmdTest)
rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "Enable debug mode")
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "The log level to use. Valid values are \"debug\", \"info\", \"warn\", \"error\", and \"fatal\".")
logger = initLogger(logLevel)
logger, err := initLogger(logLevel)
if err != nil {
panic(err)
}
if debug {
logger().Debug("debug mode enabled")
}
Expand Down Expand Up @@ -207,21 +210,23 @@ func initChatwork(logger func() *logrus.Entry) *notify.Chatwork {
return chatwork
}

func initLogger(logLevel string) func() *logrus.Entry {
func initLogger(logLevel string) (func() *logrus.Entry, error) {
logr := logrus.New()
logr.SetFormatter(&logrus.JSONFormatter{})
level, err := logrus.ParseLevel(logLevel)

if err != nil {
logr.Fatal("invalid log level: ", err)
logr.Infof("invalid log level: %v", err)
return nil, err
}

logr.SetLevel(level)

return func() *logrus.Entry {
_, file, line, ok := runtime.Caller(1)
if !ok {
panic("Could not get context info for logger!")
logr.Warn("Could not get context info for logger!")
return logr.WithField("file", "unknown")
}

filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line)
Expand All @@ -230,5 +235,5 @@ func initLogger(logLevel string) func() *logrus.Entry {
//fn := funcname[lastSlashIndex+1:]
//return logr.WithField("file", filename).WithField("function", fn)
return logr.WithField("file", filename)
}
}, nil
}

0 comments on commit f3d0374

Please sign in to comment.