Skip to content

Commit

Permalink
log filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
OneOfOne committed May 31, 2024
1 parent 4c5217c commit 792bb2c
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
31 changes: 31 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package gserv

import (
"bytes"
"io"
"log"
"os"
)

type filteredLogger struct {
matches [][]byte
w io.Writer
}

func (fl *filteredLogger) Write(p []byte) (n int, err error) {
for _, m := range fl.matches {
if bytes.Contains(p, m) {
return
}
}
return fl.w.Write(p)
}

func FilteredLogger(flags int, msgs ...string) *log.Logger {
var fl = &filteredLogger{w: os.Stderr}
for _, m := range msgs {
fl.matches = append(fl.matches, []byte(m))
}

return log.New(fl, "gserv: ", flags)
}
1 change: 1 addition & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ func (s *Server) Logf(f string, args ...any) {

func (s *Server) logfStack(n int, f string, args ...any) {
lg := s.opts.Logger
log.Println(lg)
if lg == nil {
lg = log.Default()
}
Expand Down
6 changes: 4 additions & 2 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ func init() {
log.SetFlags(0)
}

var setErrLogger = SetErrLogger(FilteredLogger(log.Lshortfile, "/panic"))

var testData = []struct {
path string
*JSONResponse
Expand All @@ -42,7 +44,7 @@ func newServerAndWait(t *testing.T, addr string) *Server {
if testing.Verbose() {
s = New()
} else {
s = New(SetErrLogger(nil)) // don't need the spam with panics for the /panic handler
s = New(setErrLogger) // don't need the spam with panics for the /panic handler
}
if addr == "" {
addr = "127.0.0.1:0"
Expand Down Expand Up @@ -98,7 +100,7 @@ func TestServer(t *testing.T) {
if testing.Verbose() {
srv = New(SetCatchPanics(true))
} else {
srv = New(SetCatchPanics(true), SetErrLogger(nil)) // don't need the spam with panics for the /panic handler
srv = New(SetCatchPanics(true), setErrLogger) // don't need the spam with panics for the /panic handler
}

// srv.PanicHandler = func(ctx *Context, v any) {
Expand Down

0 comments on commit 792bb2c

Please sign in to comment.