-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
55 lines (49 loc) · 1.27 KB
/
middleware.go
File metadata and controls
55 lines (49 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package skedulr
import (
"context"
"fmt"
"runtime/debug"
"time"
)
// Middleware is a function that wraps a Job to add behavior before or after execution.
type Middleware func(Job) Job
// Recovery returns a middleware that captures panics within a job,
// logs them using the provided logger, and calls an optional onPanic function.
func Recovery(l Logger, onPanic func()) Middleware {
return func(next Job) Job {
return func(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
if l != nil {
l.Error("panic captured in job", fmt.Errorf("%v", r), "stack", string(debug.Stack()))
}
if onPanic != nil {
onPanic()
}
}
}()
return next(ctx)
}
}
}
// Logging returns a middleware that logs the start and completion of a job.
func Logging(l Logger) Middleware {
return func(next Job) Job {
return func(ctx context.Context) error {
if l == nil {
return next(ctx)
}
id := TaskID(ctx)
l.Info("task started", "task_id", id)
start := time.Now()
err := next(ctx)
dur := time.Since(start)
if err != nil {
l.Error("task finished with error", err, "task_id", id, "duration", dur)
} else {
l.Info("task finished successfully", "task_id", id, "duration", dur)
}
return err
}
}
}