88 "strconv"
99 "strings"
1010 "sync"
11+ "sync/atomic"
1112 "time"
1213)
1314
@@ -18,6 +19,30 @@ const (
1819 termMsgJust = 40
1920)
2021
22+ // locationTrims are trimmed for display to avoid unwieldy log lines.
23+ var locationTrims = []string {
24+ "github.com/ethereum/go-ethereum/" ,
25+ "github.com/ethereum/ethash/" ,
26+ }
27+
28+ // PrintOrigins sets or unsets log location (file:line) printing for terminal
29+ // format output.
30+ func PrintOrigins (print bool ) {
31+ if print {
32+ atomic .StoreUint32 (& locationEnabled , 1 )
33+ } else {
34+ atomic .StoreUint32 (& locationEnabled , 0 )
35+ }
36+ }
37+
38+ // locationEnabled is an atomic flag controlling whether the terminal formatter
39+ // should append the log locations too when printing entries.
40+ var locationEnabled uint32
41+
42+ // locationLength is the maxmimum path length encountered, which all logs are
43+ // padded to to aid in alignment.
44+ var locationLength uint32
45+
2146type Format interface {
2247 Format (r * Record ) []byte
2348}
@@ -64,12 +89,33 @@ func TerminalFormat() Format {
6489
6590 b := & bytes.Buffer {}
6691 lvl := strings .ToUpper (r .Lvl .String ())
67- if color > 0 {
68- fmt .Fprintf (b , "\x1b [%dm%s\x1b [0m[%s] %s " , color , lvl , r .Time .Format (termTimeFormat ), r .Msg )
92+ if atomic .LoadUint32 (& locationEnabled ) != 0 {
93+ // Log origin printing was requested, format the location path and line number
94+ location := fmt .Sprintf ("%+v" , r .Call )
95+ for _ , prefix := range locationTrims {
96+ location = strings .TrimPrefix (location , prefix )
97+ }
98+ // Maintain the maximum location length for fancyer alignment
99+ align := int (atomic .LoadUint32 (& locationLength ))
100+ if align < len (location ) {
101+ align = len (location )
102+ atomic .StoreUint32 (& locationLength , uint32 (align ))
103+ }
104+ padding := strings .Repeat (" " , align - len (location ))
105+
106+ // Assemble and print the log heading
107+ if color > 0 {
108+ fmt .Fprintf (b , "\x1b [%dm%s\x1b [0m[%s|%s]%s %s " , color , lvl , r .Time .Format (termTimeFormat ), location , padding , r .Msg )
109+ } else {
110+ fmt .Fprintf (b , "[%s] [%s|%s]%s %s " , lvl , r .Time .Format (termTimeFormat ), location , padding , r .Msg )
111+ }
69112 } else {
70- fmt .Fprintf (b , "[%s] [%s] %s " , lvl , r .Time .Format (termTimeFormat ), r .Msg )
113+ if color > 0 {
114+ fmt .Fprintf (b , "\x1b [%dm%s\x1b [0m[%s] %s " , color , lvl , r .Time .Format (termTimeFormat ), r .Msg )
115+ } else {
116+ fmt .Fprintf (b , "[%s] [%s] %s " , lvl , r .Time .Format (termTimeFormat ), r .Msg )
117+ }
71118 }
72-
73119 // try to justify the log output for short messages
74120 if len (r .Ctx ) > 0 && len (r .Msg ) < termMsgJust {
75121 b .Write (bytes .Repeat ([]byte {' ' }, termMsgJust - len (r .Msg )))
0 commit comments