Skip to content

Commit

Permalink
use init for gRPC log redirection (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
ktong authored Apr 27, 2024
1 parent 681cd0e commit f80400a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
2 changes: 2 additions & 0 deletions grpc/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
// Use of this source code is governed by a MIT license found in the LICENSE file.

// Package grpc provides opinionated production-ready gRPC server and client.
//
// It also redirect gRPC log to slog using init function.
package grpc
17 changes: 17 additions & 0 deletions grpc/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (c) 2024 The nilgo authors
// Use of this source code is governed by a MIT license found in the LICENSE file.

package grpc

import (
"log/slog"

"google.golang.org/grpc/grpclog"

"github.com/nil-go/nilgo/grpc/internal"
)

func init() { //nolint:gochecknoinits
// Redirect gRPC log to slog.
grpclog.SetLoggerV2(internal.NewSlogger(slog.Default().Handler()))
}
11 changes: 4 additions & 7 deletions grpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"sync"

"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
Expand All @@ -27,11 +26,9 @@ import (
//
// It wraps grpc.NewServer with built-in interceptors, e.g recovery, log buffering, and statsHandler.
func NewServer(opts ...grpc.ServerOption) *grpc.Server {
// Redirect gRPC log to slog.
grpclog.SetLoggerV2(internal.NewSlogger(slog.Default().Handler()))

handler := slog.Default().Handler()
builtInOpts := []grpc.ServerOption{grpc.WaitForHandlers(true)}
if internal.IsSamplingHandler(slog.Default().Handler()) {
if internal.IsSamplingHandler(handler) {
builtInOpts = append(builtInOpts,
grpc.ChainUnaryInterceptor(internal.BufferUnaryInterceptor),
grpc.ChainStreamInterceptor(internal.BufferStreamInterceptor),
Expand All @@ -40,8 +37,8 @@ func NewServer(opts ...grpc.ServerOption) *grpc.Server {
// Add recovery interceptors after buffer interceptors so the info logs in the same session
// can be emitted for trouble shooting.
builtInOpts = append(builtInOpts,
grpc.ChainUnaryInterceptor(internal.RecoveryUnaryInterceptor(slog.Default().Handler())),
grpc.ChainStreamInterceptor(internal.RecoveryStreamInterceptor(slog.Default().Handler())),
grpc.ChainUnaryInterceptor(internal.RecoveryUnaryInterceptor(handler)),
grpc.ChainStreamInterceptor(internal.RecoveryStreamInterceptor(handler)),
)
builtInOpts = append(builtInOpts, opts...)

Expand Down

0 comments on commit f80400a

Please sign in to comment.