Skip to content

Commit bd38a60

Browse files
committed
Factor log decorating logic out into a Writer
... to make it usable in more places, and for encapsulation
1 parent 760f10f commit bd38a60

1 file changed

Lines changed: 40 additions & 2 deletions

File tree

internal/api/js/chrome/chrome.go

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ import (
1212
"net"
1313
"net/http"
1414
"os"
15+
"os/exec"
1516
"path/filepath"
1617
"strconv"
1718
"sync"
19+
"syscall"
1820
"time"
1921

2022
"github.com/chromedp/cdproto/runtime"
@@ -70,16 +72,52 @@ type Browser struct {
7072
Cancel func()
7173
}
7274

75+
// colouredLogWriter is an implementation of `io.Writer` which wraps an `os.File`, adding the date and logPrefix to each line,
76+
// and decorating the text in a specific colour.
77+
type coloredLogWriter struct {
78+
colour string
79+
logPrefix string
80+
output *os.File
81+
}
82+
83+
func (w coloredLogWriter) Write(p []byte) (n int, err error) {
84+
_, err = w.output.WriteString(w.colour)
85+
if err != nil {
86+
return
87+
}
88+
89+
last := byte('\n')
90+
for _, c := range p {
91+
// If this is the first byte after a newline, add the date and prefix
92+
if last == '\n' {
93+
_, err = w.output.WriteString(time.Now().Format(time.RFC3339) + " " + w.logPrefix + " ")
94+
if err != nil {
95+
return
96+
}
97+
}
98+
_, err = w.output.Write([]byte{c})
99+
if err != nil {
100+
return
101+
}
102+
n += 1
103+
last = c
104+
}
105+
106+
ansiResetForeground := "\x1b[39m"
107+
_, err = w.output.WriteString(ansiResetForeground)
108+
return
109+
}
110+
73111
func RunHeadless(logPrefix string, onConsoleLog func(s string), requiresPersistence bool, listenPort int) (*Browser, error) {
74112
ansiRedForeground := "\x1b[31m"
75113
ansiYellowForeground := "\x1b[33m"
76114
ansiResetForeground := "\x1b[39m"
77115

78116
// colorifyError returns a log format function which prints its input with a given prefix and colour.
79117
colorifyError := func(colour string, prefix string) func(format string, args ...any) {
118+
writer := coloredLogWriter{colour: colour, logPrefix: logPrefix + "[chromedp " + prefix + "]", output: os.Stdout}
80119
return func(format string, args ...any) {
81-
format = ansiRedForeground + time.Now().Format(time.RFC3339) + " " + logPrefix + "[chromedp " + prefix + "] " + format + ansiResetForeground + "\n"
82-
fmt.Printf(format, args...)
120+
fmt.Fprintf(writer, format, args...)
83121
}
84122
}
85123
opts := chromedp.DefaultExecAllocatorOptions[:]

0 commit comments

Comments
 (0)