MCPcopy Create free account
hub / github.com/riverqueue/river / ExampleNewMiddleware

Function ExampleNewMiddleware

riverlog/example_new_middleware_test.go:37–100  ·  view source on GitHub ↗

ExampleNewMiddleware demonstrates the use of riverlog middleware to inject a logger into context that'll persist its output onto the job record.

()

Source from the content-addressed store, hash-verified

35// ExampleNewMiddleware demonstrates the use of riverlog middleware to inject a
36// logger into context that'll persist its output onto the job record.
37func ExampleNewMiddleware() {
38 ctx := context.Background()
39
40 dbPool, err := pgxpool.New(ctx, riversharedtest.TestDatabaseURL())
41 if err != nil {
42 panic(err)
43 }
44 defer dbPool.Close()
45
46 workers := river.NewWorkers()
47 river.AddWorker(workers, &LoggingWorker{})
48
49 riverClient, err := river.NewClient(riverpgxv5.New(dbPool), initTestConfig(ctx, dbPool, &river.Config{
50 Queues: map[string]river.QueueConfig{
51 river.QueueDefault: {MaxWorkers: 100},
52 },
53 Middleware: []rivertype.Middleware{
54 riverlog.NewMiddleware(func(w io.Writer) slog.Handler {
55 // We have to use a specialized ReplacedAttr without level or
56 // timestamps to make test output reproducible, but in reality
57 // this would as simple as something like:
58 //
59 // return slog.NewJSONHandler(w, nil)
60 return slog.NewTextHandler(w, &slog.HandlerOptions{ReplaceAttr: slogutil.NoLevelTime})
61 }, nil),
62 },
63 Workers: workers,
64 }))
65 if err != nil {
66 panic(err)
67 }
68
69 // Out of example scope, but used to wait until a job is worked.
70 subscribeChan, subscribeCancel := riverClient.Subscribe(river.EventKindJobCompleted)
71 defer subscribeCancel()
72
73 if err := riverClient.Start(ctx); err != nil {
74 panic(err)
75 }
76
77 _, err = riverClient.Insert(ctx, LoggingArgs{}, nil)
78 if err != nil {
79 panic(err)
80 }
81
82 // Wait for job to complete, extract log data out of metadata, and print it.
83 for _, event := range riversharedtest.WaitOrTimeoutN(testutil.PanicTB(), subscribeChan, 1) {
84 var metadataWithLog metadataWithLog
85 if err := json.Unmarshal(event.Job.Metadata, &metadataWithLog); err != nil {
86 panic(err)
87 }
88 for _, logAttempt := range metadataWithLog.RiverLog {
89 fmt.Print(logAttempt.Log)
90 }
91 }
92
93 if err := riverClient.Stop(ctx); err != nil {
94 panic(err)

Callers

nothing calls this directly

Calls 14

TestDatabaseURLFunction · 0.92
NewWorkersFunction · 0.92
AddWorkerFunction · 0.92
NewClientFunction · 0.92
NewFunction · 0.92
NewMiddlewareFunction · 0.92
WaitOrTimeoutNFunction · 0.92
PanicTBFunction · 0.92
SubscribeMethod · 0.80
InsertMethod · 0.80
initTestConfigFunction · 0.70
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…