!5285odin/log-caller-cwd → developb20a294c5b

Console log writer looks up the working directory once

AI-generatedEverything on this page was written by an AI agent from the diff: the summaries, the narration, the diagrams, the flags and the glossary. It can be wrong or incomplete, so check it against the code before you rely on it.

1commits
3files
192lines changed
77lines to read
−32%ns per log line (bench)
0state changes

Where the diff is

Tests1 files · 115 lines

cmd/thornode/console_log_test.go+115 −0
1byte-identical vs SDK2NO_COLOR on/off3trace stack kept4JSON + filters untouched

2-minute explainer

What changed

Wasted syscall

os.Getwd on every log line; -trimpath callers never shorten.

log lineos.Getwdfilepath.Relunchanged path

Cached cwd

zerolog's caller formatter with Getwd called once at start.

consoleLogOutputconsoleFormatCallerconsoleColorize

Fallbacks

JSON output and module-filtered levels keep the SDK logger.

--log_format json → unchangedconsensus:info,*:error → unchangedsingle level → new writer

Evidence

Bench −32%/line; replay drops 4 s of os.Getwd; output byte-identical.

Look here first

Rebuilt writer must match SDK optionsOnly NoColor, TimeFormat, Out are copied; any other SDK console option is lost. SDK source not checked here; test compares output.console_log.go:35 ↗verify
26+ if v.GetString(flags.FlagLogFormat) == flags.OutputFormatJSON {
27+ return zl
28+ }
29+ if lvl := v.GetString(flags.FlagLogLevel); lvl != "" {
30+ if _, err := zerolog.ParseLevel(lvl); err != nil {
31+ return zl
32+ }
33+ }
34+ noColor := v.GetBool(flags.FlagLogNoColor)
35+ logger := zl.Output(zerolog.ConsoleWriter{
36+ Out: out,
37+ NoColor: noColor,
38+ TimeFormat: time.Kitchen,
39+ FormatCaller: consoleFormatCaller(noColor),
40+ })
41+ return &logger
42+}
43+
44+// consoleFormatCaller is zerolog's default caller formatter with the working
45+// directory looked up once.
46+func consoleFormatCaller(noColor bool) zerolog.Formatter {
47+ cwd, cwdErr := os.Getwd()
48+ return func(i any) string {
Module-filter detection via ParseLevelAnything ParseLevel rejects falls back to SDK; must match the SDK's own filter parsing exactly.console_log.go:29 ↗careful
20+//
21+// The writer is otherwise the one cosmossdk.io/log builds for the server's log
22+// flags, and zerolog's Output keeps the logger's level, hooks and context. For
23+// JSON output and for module filtered log levels, which the SDK writes through
24+// writers this can't rebuild, zl is returned as is.
25+func consoleLogOutput(zl *zerolog.Logger, v *viper.Viper, out io.Writer) *zerolog.Logger {
26+ if v.GetString(flags.FlagLogFormat) == flags.OutputFormatJSON {
27+ return zl
28+ }
29+ if lvl := v.GetString(flags.FlagLogLevel); lvl != "" {
30+ if _, err := zerolog.ParseLevel(lvl); err != nil {
31+ return zl
32+ }
33+ }
34+ noColor := v.GetBool(flags.FlagLogNoColor)
35+ logger := zl.Output(zerolog.ConsoleWriter{
36+ Out: out,
37+ NoColor: noColor,
38+ TimeFormat: time.Kitchen,
39+ FormatCaller: consoleFormatCaller(noColor),
40+ })
41+ return &logger
42+}
Copied private zerolog colorizeDrifts silently on zerolog upgrade; TestConsoleLogOutputMatchesSDK is the only guard.console_log.go:66 ↗careful
57+ }
58+ }
59+ c = consoleColorize(c, 1, noColor) + consoleColorize(" >", 36, noColor)
60+ }
61+ return c
62+ }
63+}
64+
65+// consoleColorize is zerolog's colorize, which isn't exported.
66+func consoleColorize(s any, c int, disabled bool) string {
67+ e := os.Getenv("NO_COLOR")
68+ if e != "" || c == 0 {
69+ disabled = true
70+ }
71+
72+ if disabled {
73+ return fmt.Sprintf("%s", s)
74+ }
75+ return fmt.Sprintf("\x1b[%dm%v\x1b[0m", c, s)
76+}
cwd frozen at PreRunELater chdir would not be reflected; harmless for -trimpath module paths.console_log.go:47 ↗look
38+ TimeFormat: time.Kitchen,
39+ FormatCaller: consoleFormatCaller(noColor),
40+ })
41+ return &logger
42+}
43+
44+// consoleFormatCaller is zerolog's default caller formatter with the working
45+// directory looked up once.
46+func consoleFormatCaller(noColor bool) zerolog.Formatter {
47+ cwd, cwdErr := os.Getwd()
48+ return func(i any) string {
49+ var c string
50+ if cc, ok := i.(string); ok {
51+ c = cc
52+ }
53+ if len(c) > 0 {
54+ if cwdErr == nil {
55+ if rel, err := filepath.Rel(cwd, c); err == nil {
56+ c = rel
57+ }
58+ }
59+ c = consoleColorize(c, 1, noColor) + consoleColorize(" >", 36, noColor)
60+ }
Applied before caller skip framesOutput copies level, hooks, context; CallerWithSkipFrameCount(3) added afterwards, unchanged.commands.go:171 ↗look
162162
163163 // Bind flags to the Context's Viper so the app construction can set
164164 // options accordingly.
165165 if err := serverCtx.Viper.BindPFlags(cmd.Flags()); err != nil {
166166 return fmt.Errorf("fail to bind flags,err: %w", err)
167167 }
168168
169169 // replace sdk logger with thorlog
170170 if zl, ok := serverCtx.Logger.Impl().(*zerolog.Logger); ok {
171+ zl = consoleLogOutput(zl, serverCtx.Viper, cmd.OutOrStdout())
171172 logger := zl.With().CallerWithSkipFrameCount(3).Logger()
172173 serverCtx.Logger = thorlog.SdkLogWrapper{
173174 Logger: &logger,
174175 }
175176 }
176177
177178 // Wrap the logger to detect CometBFT consensus failures and crash the
178179 // process instead of hanging indefinitely with a dead consensus goroutine.
179180 serverCtx.Logger = NewConsensusFailureLogger(serverCtx.Logger)
180181 return server.SetCmdServerContext(startCmd, serverCtx)
181182 }
182183 wasm.AddModuleInitFlags(startCmd)
183184 ebifrost.AddModuleInitFlags(startCmd)
Equality test is the safety netBoth loggers log identical lines; NO_COLOR via t.Setenv, fixed timestamp.console_log_test.go:62 ↗look
53+ for _, settings := range []map[string]any{
54+ {},
55+ {flags.FlagLogLevel: "info"},
56+ {flags.FlagLogLevel: "debug", flags.FlagLogNoColor: true},
57+ {flags.FlagLogLevel: "error", flags.FlagLogFormat: "plain"},
58+ } {
59+ var want, got bytes.Buffer
60+ sdk, _ := sdkConsoleLogger(t, settings, &want)
61+ zl, v := sdkConsoleLogger(t, settings, io.Discard)
62+ for _, l := range []*zerolog.Logger{sdk, consoleLogOutput(zl, v, &got)} {
63+ logLines(*l)
64+ }
65+ if want.Len() == 0 {
66+ t.Fatalf("%v: nothing logged", settings)
67+ }
68+ if got.String() != want.String() {
69+ t.Errorf("NO_COLOR=%q %v:\nsdk: %q\nthis: %q", noColorEnv, settings, want.String(), got.String())
70+ }
71+ }
72+ }
73+}
74+
75+// With --trace the SDK logger adds error stacks; the stack's JSON key order

Ask an AI about this change

Chat assistantClaude, ChatGPT, … (reads a link)

Coding agentClaude Code, Cursor, … (reads the repo)

The context file is context.md. Use Copy with context for an AI that can't open links; it pastes the whole file in.

Glossary

-trimpath
Go build flag that strips file system paths, so callers show module paths that cannot be made relative to the cwd. go build docs ↗
NO_COLOR
Environment variable that disables ANSI colours in zerolog's console output; honoured by the copied colorize. no-color.org ↗
os.Getwd
Returns the working directory; it stats . and $PWD each call, which was the per-line cost. pkg.go.dev os.Getwd ↗
SdkLogWrapper
thornode's wrapper that adapts its zerolog logger to the SDK logger interface. log/log.go ↗
zerolog
The structured logging library behind cosmossdk.io/log; ConsoleWriter renders human-readable lines. rs/zerolog ↗