Skip to content
This repository has been archived by the owner on Mar 21, 2024. It is now read-only.

Commit

Permalink
Split logrus config out (#65)
Browse files Browse the repository at this point in the history
- Keep main.go as simple as possiable

- Add `BYTOM_DEBUG` environment variable to set the log level to DEBUG
  • Loading branch information
liuchengxu authored and gguoss committed Oct 21, 2017
1 parent 83db836 commit 66fb5bb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 33 deletions.
44 changes: 44 additions & 0 deletions cmd/bytomd/log_hook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
log "github.com/sirupsen/logrus"
"os"
"path"
"runtime"
"strings"
)

type ContextHook struct{}

func (hook ContextHook) Levels() []log.Level {
return log.AllLevels
}

func (hook ContextHook) Fire(entry *log.Entry) error {
pc := make([]uintptr, 3, 3)
cnt := runtime.Callers(6, pc)

for i := 0; i < cnt; i++ {
fu := runtime.FuncForPC(pc[i] - 1)
name := fu.Name()
if !strings.Contains(name, "github.com/Sirupsen/log") {
file, line := fu.FileLine(pc[i] - 1)
entry.Data["file"] = path.Base(file)
entry.Data["func"] = path.Base(name)
entry.Data["line"] = line
break
}
}
return nil
}

func init() {
log.SetFormatter(&log.TextFormatter{FullTimestamp: true})

// If environment variable BYTOM_DEBUG is not empty,
// then add the hook to logrus and set the log level to DEBUG
if os.Getenv("BYTOM_DEBUG") != "" {
log.AddHook(ContextHook{})
log.SetLevel(log.DebugLevel)
}
}
33 changes: 0 additions & 33 deletions cmd/bytomd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,11 @@ package main

import (
"github.com/bytom/cmd/bytomd/commands"
"github.com/sirupsen/logrus"
"github.com/tendermint/tmlibs/cli"
"os"
"path"
"runtime"
"strings"
)

type ContextHook struct{}

func (hook ContextHook) Levels() []logrus.Level {
return logrus.AllLevels
}

func (hook ContextHook) Fire(entry *logrus.Entry) error {
pc := make([]uintptr, 3, 3)
cnt := runtime.Callers(6, pc)

for i := 0; i < cnt; i++ {
fu := runtime.FuncForPC(pc[i] - 1)
name := fu.Name()
if !strings.Contains(name, "github.com/Sirupsen/logrus") {
file, line := fu.FileLine(pc[i] - 1)
entry.Data["file"] = path.Base(file)
entry.Data["func"] = path.Base(name)
entry.Data["line"] = line
break
}
}
return nil
}

func init() {
logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
}

func main() {
logrus.AddHook(ContextHook{})
cmd := cli.PrepareBaseCmd(commands.RootCmd, "TM", os.ExpandEnv("./.bytomd"))
cmd.Execute()
}

0 comments on commit 66fb5bb

Please sign in to comment.