From 204803d051013ec924b3632ab71fd4a3397e42c3 Mon Sep 17 00:00:00 2001 From: A-gmaE-programmer Date: Mon, 22 Jul 2024 01:29:44 +0800 Subject: [PATCH] Add support for setting an output file for logs instead of stdout --- lemon/cli.go | 1 + lemon/flag.go | 1 + lemon/main.go | 1 + main.go | 11 ++++++++++- 4 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lemon/cli.go b/lemon/cli.go index 82e8c9e..b64f66a 100644 --- a/lemon/cli.go +++ b/lemon/cli.go @@ -45,6 +45,7 @@ type CLI struct { LineEnding string LogLevel int Timeout time.Duration + LogFile string Help bool diff --git a/lemon/flag.go b/lemon/flag.go index 8b05207..1b51a08 100644 --- a/lemon/flag.go +++ b/lemon/flag.go @@ -79,6 +79,7 @@ func (c *CLI) flags() *flag.FlagSet { flags.BoolVar(&c.NoFallbackMessages, "no-fallback-messages", false, "Do not show fallback messages") flags.DurationVar(&c.Timeout, "rpc-timeout", 100*time.Millisecond, "RPC timeout") flags.IntVar(&c.LogLevel, "log-level", 1, "Log level") + flags.StringVar(&c.LogFile, "log-file", "", "Log output to a file") return flags } diff --git a/lemon/main.go b/lemon/main.go index 62e871c..fc5ddb1 100644 --- a/lemon/main.go +++ b/lemon/main.go @@ -23,6 +23,7 @@ Options: --trans-loopback=true Translate loopback address [open subcommand only] --trans-localfile=true Translate local file path [open subcommand only] --log-level=1 Log level [4 = Critical, 0 = Debug] + --log-file=.lemonlog[.json] Output logs to a custom file instead of stdout --help Show this message diff --git a/main.go b/main.go index 018d73f..8d2c445 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "strings" log "github.com/inconshreveable/log15" @@ -39,7 +40,15 @@ func Do(c *lemon.CLI, args []string) int { } logLevel := logLevelMap[c.LogLevel] - logger.SetHandler(log.LvlFilterHandler(logLevel, log.StdoutHandler)) + logOutHandler := log.StdoutHandler + if len(c.LogFile) > 0 { + logFormat := log.LogfmtFormat() + if strings.HasSuffix(c.LogFile, ".json") { + logFormat = log.JsonFormat() + } + logOutHandler = log.Must.FileHandler(c.LogFile, logFormat) + } + logger.SetHandler(log.LvlFilterHandler(logLevel, logOutHandler)) if c.Help { fmt.Fprint(c.Err, lemon.Usage)