Skip to content

Commit ae6bbd0

Browse files
authored
Merge pull request hoisie#202 from hoisie/tty-colors
Clean up the logic for color logging
2 parents 6f78904 + 22000d1 commit ae6bbd0

File tree

2 files changed

+50
-13
lines changed

2 files changed

+50
-13
lines changed

server.go

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,6 @@ func (s *Server) tryServingFile(name string, req *http.Request, w http.ResponseW
269269

270270
func (s *Server) logRequest(ctx Context, sTime time.Time) {
271271
//log the request
272-
var logEntry bytes.Buffer
273272
req := ctx.Request
274273
requestPath := req.URL.Path
275274

@@ -285,22 +284,30 @@ func (s *Server) logRequest(ctx Context, sTime time.Time) {
285284
client = req.RemoteAddr
286285
}
287286

288-
if s.Config.ColorOutput {
289-
fmt.Fprintf(&logEntry, "%s - \x1b[32;1m%s %s\x1b[0m - %v", client, req.Method, requestPath, duration)
290-
} else {
291-
fmt.Fprintf(&logEntry, "%s - %s %s - %v", client, req.Method, requestPath, duration)
292-
}
293-
287+
var logEntry bytes.Buffer
288+
logEntry.WriteString(client)
289+
logEntry.WriteString(" - " + s.ttyGreen(req.Method+" "+requestPath))
290+
logEntry.WriteString(" - " + duration.String())
294291
if len(ctx.Params) > 0 {
295-
if s.Config.ColorOutput {
296-
fmt.Fprintf(&logEntry, " - \x1b[37;1mParams: %v\x1b[0m\n", ctx.Params)
297-
} else {
298-
fmt.Fprintf(&logEntry, " - Params: %v\n", ctx.Params)
299-
}
292+
logEntry.WriteString(" - " + s.ttyWhite(fmt.Sprintf("Params: %v\n", ctx.Params)))
300293
}
301-
302294
ctx.Server.Logger.Print(logEntry.String())
295+
}
296+
297+
func (s *Server) ttyGreen(msg string) string {
298+
return s.ttyColor(msg, ttyCodes.green)
299+
}
300+
301+
func (s *Server) ttyWhite(msg string) string {
302+
return s.ttyColor(msg, ttyCodes.white)
303+
}
303304

305+
func (s *Server) ttyColor(msg string, colorCode string) string {
306+
if s.Config.ColorOutput {
307+
return colorCode + msg + ttyCodes.reset
308+
} else {
309+
return msg
310+
}
304311
}
305312

306313
// the main route handler in web.go

ttycolors.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package web
2+
3+
import (
4+
"golang.org/x/crypto/ssh/terminal"
5+
"syscall"
6+
)
7+
8+
var ttyCodes struct {
9+
green string
10+
white string
11+
reset string
12+
}
13+
14+
func init() {
15+
ttyCodes.green = ttyBold("32")
16+
ttyCodes.white = ttyBold("37")
17+
ttyCodes.reset = ttyEscape("0")
18+
}
19+
20+
func ttyBold(code string) string {
21+
return ttyEscape("1;" + code)
22+
}
23+
24+
func ttyEscape(code string) string {
25+
if terminal.IsTerminal(syscall.Stdout) {
26+
return "\x1b[" + code + "m"
27+
} else {
28+
return ""
29+
}
30+
}

0 commit comments

Comments
 (0)