Skip to content

Commit

Permalink
add option to save log to file (#2)
Browse files Browse the repository at this point in the history
Co-authored-by: wangsai <wangsai@huobi.com>
  • Loading branch information
wangsai-silence and wangsai committed Nov 25, 2020
1 parent cbdff65 commit 119e2d2
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 12 deletions.
34 changes: 22 additions & 12 deletions internal/debug/flags.go
Expand Up @@ -41,6 +41,11 @@ var (
Usage: "Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail",
Value: 3,
}
logPathFlag = cli.StringFlag{
Name: "logpath",
Usage: "File path for log files",
Value: "",
}
vmoduleFlag = cli.StringFlag{
Name: "vmodule",
Usage: "Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)",
Expand Down Expand Up @@ -114,7 +119,7 @@ var (

// Flags holds all command-line flags required for debugging.
var Flags = []cli.Flag{
verbosityFlag, vmoduleFlag, backtraceAtFlag, debugFlag,
verbosityFlag, logPathFlag, vmoduleFlag, backtraceAtFlag, debugFlag,
pprofFlag, pprofAddrFlag, pprofPortFlag, memprofilerateFlag,
blockprofilerateFlag, cpuprofileFlag, traceFlag,
}
Expand All @@ -125,24 +130,29 @@ var DeprecatedFlags = []cli.Flag{
}

var (
ostream log.Handler
glogger *log.GlogHandler
)

func init() {
usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
output := io.Writer(os.Stderr)
if usecolor {
output = colorable.NewColorableStderr()
}
ostream = log.StreamHandler(output, log.TerminalFormat(usecolor))
glogger = log.NewGlogHandler(ostream)
}

// Setup initializes profiling and logging based on the CLI flags.
// It should be called as early as possible in the program.
func Setup(ctx *cli.Context) error {
// logging
usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"

var handler log.Handler
if ctx.GlobalString(logPathFlag.Name) != "" {
rConfig := log.NewRotateConfig()
rConfig.LogDir = ctx.GlobalString(logPathFlag.Name)
handler = log.NewFileRotateHandler(rConfig, log.TerminalFormat(usecolor))
} else {
output := io.Writer(os.Stderr)
if usecolor {
output = colorable.NewColorableStderr()
}
handler = log.StreamHandler(output, log.TerminalFormat(usecolor))
}
glogger = log.NewGlogHandler(handler)

log.PrintOrigins(ctx.GlobalBool(debugFlag.Name))
glogger.Verbosity(log.Lvl(ctx.GlobalInt(verbosityFlag.Name)))
glogger.Vmodule(ctx.GlobalString(vmoduleFlag.Name))
Expand Down
84 changes: 84 additions & 0 deletions log/handler_rotate.go
@@ -0,0 +1,84 @@
// Copyright 2020 YOUCHAIN FOUNDATION LTD.
// This file is part of the go-youchain library.
//
// The go-youchain library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-youchain library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-youchain library. If not, see <http://www.gnu.org/licenses/>.

package log

import (
"fmt"
"os"
"path"
"path/filepath"

"gopkg.in/natefinch/lumberjack.v2"
)

type RotateConfig struct {
LogDir string `json:"log_dir"`
Filename string `json:"filename"` // file name
MaxAge int `json:"max_age"` // max age
MaxSize int `json:"max_size"` // MB
MaxBackups int `json:"max_backups"`
}

var defaultConfig = &RotateConfig{
LogDir: "logs",
Filename: "chain.log",
MaxSize: 100,
MaxAge: 7,
MaxBackups: 10,
}

func NewRotateConfig() *RotateConfig {
conf := *defaultConfig
return &conf
}

func NewFileRotateHandler(config *RotateConfig, format Format) Handler {
if err := config.setup(); err != nil {
fmt.Println(err.Error())
return nil
}

logDir := config.LogDir
if !filepath.IsAbs(logDir) {
logDir, _ = filepath.Abs(logDir)
}
log := lumberjack.Logger{
Filename: path.Join(logDir, config.Filename),
MaxSize: config.MaxSize, // megabytes
MaxBackups: config.MaxBackups,
MaxAge: config.MaxAge, // days
LocalTime: true,
Compress: true, // disabled by default
}

h := StreamHandler(&log, format)

return FuncHandler(func(r *Record) error {
return h.Log(r)
})
}

func (c *RotateConfig) setup() error {
if len(c.LogDir) == 0 {
panic("Failed to parse logger folder:" + c.LogDir + ".")
}

if err := os.MkdirAll(c.LogDir, 0700); err != nil {
panic("Failed to create logger folder:" + c.LogDir + ". err:" + err.Error())
}
return nil
}

0 comments on commit 119e2d2

Please sign in to comment.