Fix defaultLogEntry.Panic not respecting NoColor setting (#1050)

Panic() called PrintPrettyStack() which hardcodes useColor=true.
Thread the useColor flag from defaultLogEntry through to
prettyStack.parse() so it respects DefaultLogFormatter.NoColor.

Fixes #1042
This commit is contained in:
Arif Dogan 2026-07-05 17:38:14 +02:00 committed by GitHub
parent d7b767bcbe
commit 878fe71fc9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 34 additions and 4 deletions

View file

@ -166,7 +166,7 @@ func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed t
}
func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
PrintPrettyStack(v)
printPrettyStack(v, l.useColor)
}
func init() {

View file

@ -52,9 +52,13 @@ func Recoverer(next http.Handler) http.Handler {
var recovererErrorWriter io.Writer = os.Stderr
func PrintPrettyStack(rvr interface{}) {
printPrettyStack(rvr, true)
}
func printPrettyStack(rvr interface{}, useColor bool) {
debugStack := debug.Stack()
s := prettyStack{}
out, err := s.parse(debugStack, rvr)
out, err := s.parse(debugStack, rvr, useColor)
if err == nil {
recovererErrorWriter.Write(out)
} else {
@ -66,9 +70,8 @@ func PrintPrettyStack(rvr interface{}) {
type prettyStack struct {
}
func (s prettyStack) parse(debugStack []byte, rvr interface{}) ([]byte, error) {
func (s prettyStack) parse(debugStack []byte, rvr interface{}, useColor bool) ([]byte, error) {
var err error
useColor := true
buf := &bytes.Buffer{}
cW(buf, false, bRed, "\n")

View file

@ -12,6 +12,10 @@ import (
func panickingHandler(http.ResponseWriter, *http.Request) { panic("foo") }
type testPrintLogger struct{}
func (testPrintLogger) Print(v ...interface{}) {}
func TestRecoverer(t *testing.T) {
r := chi.NewRouter()
@ -41,6 +45,29 @@ func TestRecoverer(t *testing.T) {
t.Fatal("First func call line should start with ->.")
}
func TestRecovererNoColor(t *testing.T) {
oldRecovererErrorWriter := recovererErrorWriter
defer func() { recovererErrorWriter = oldRecovererErrorWriter }()
buf := &bytes.Buffer{}
recovererErrorWriter = buf
r := chi.NewRouter()
r.Use(RequestLogger(&DefaultLogFormatter{Logger: testPrintLogger{}, NoColor: true}))
r.Use(Recoverer)
r.Get("/", panickingHandler)
ts := httptest.NewServer(r)
defer ts.Close()
res, _ := testRequest(t, ts, "GET", "/", nil)
assertEqual(t, res.StatusCode, http.StatusInternalServerError)
// ANSI escape sequences start with \x1b[
if strings.Contains(buf.String(), "\x1b[") {
t.Fatal("Output should not contain ANSI color codes when NoColor is true")
}
}
func TestRecovererAbortHandler(t *testing.T) {
defer func() {
rcv := recover()