Skip to content

Commit 8f8549a

Browse files
authored
Merge pull request #669 from graph-gophers/add-logger-func
feat(log): add panic logger func
2 parents 484f3c7 + 66be227 commit 8f8549a

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

log/log.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,23 @@ import (
66
"runtime"
77
)
88

9-
// Logger is the interface used to log panics that occur during query execution. It is settable via graphql.ParseSchema
9+
// Logger is the interface used to log panics that occur during query execution. It is settable via graphql.ParseSchema.
1010
type Logger interface {
1111
LogPanic(ctx context.Context, value interface{})
1212
}
1313

14-
// DefaultLogger is the default logger used to log panics that occur during query execution
14+
// LoggerFunc is a function type that implements the Logger interface.
15+
type LoggerFunc func(ctx context.Context, value interface{})
16+
17+
// LogPanic calls the LoggerFunc with the given context and panic value.
18+
func (f LoggerFunc) LogPanic(ctx context.Context, value interface{}) {
19+
f(ctx, value)
20+
}
21+
22+
// DefaultLogger is the default logger used to log panics that occur during query execution.
1523
type DefaultLogger struct{}
1624

17-
// LogPanic is used to log recovered panic values that occur during query execution
25+
// LogPanic is used to log recovered panic values that occur during query execution.
1826
func (l *DefaultLogger) LogPanic(ctx context.Context, value interface{}) {
1927
const size = 64 << 10
2028
buf := make([]byte, size)

log/log_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package log_test
2+
3+
import (
4+
"context"
5+
"fmt"
6+
7+
"github.com/graph-gophers/graphql-go"
8+
"github.com/graph-gophers/graphql-go/log"
9+
)
10+
11+
func ExampleLoggerFunc() {
12+
logfn := log.LoggerFunc(func(ctx context.Context, err interface{}) {
13+
// Here you can handle the panic, e.g., log it or send it to an error tracking service.
14+
fmt.Printf("graphql: panic occurred: %v", err)
15+
})
16+
17+
opts := []graphql.SchemaOpt{
18+
graphql.Logger(logfn),
19+
graphql.UseFieldResolvers(),
20+
}
21+
22+
schemadef := `
23+
type Query {
24+
hello: String!
25+
}
26+
`
27+
resolver := &struct {
28+
Hello func() string
29+
}{
30+
Hello: func() string {
31+
// Simulate a panic
32+
panic("something went wrong")
33+
},
34+
}
35+
36+
schema := graphql.MustParseSchema(schemadef, resolver, opts...)
37+
// Now, when you execute a query that causes a panic, it will be logged using the provided LoggerFunc.
38+
schema.Exec(context.Background(), "{ hello }", "", nil)
39+
40+
// Output:
41+
// graphql: panic occurred: something went wrong
42+
}

0 commit comments

Comments
 (0)