Logging

Logging middleware is used to print the details of requests received or initiated by the service.

Usage

gRPC server

By passing logging.Server() in grpc.ServerOption, Kratos will print detailed request information every time a gRPC request is received.

  1. logger := log.DefaultLogger
  2. var opts = []grpc.ServerOption{
  3. grpc.Middleware(
  4. logging.Server(logger),
  5. ),
  6. }
  7. srv := grpc.NewServer(opts...)

gRPC client

By passing logging.Client() in grpc.WithMiddleware, Kratos will print detailed request information every time a grpc request is initiated.

  1. logger := log.DefaultLogger
  2. var opts = []http.ServerOption{
  3. http.Middleware(
  4. logging.Server(logger),
  5. ),
  6. }
  7. srv := http.NewServer(opts...)

HTTP client

By passing logging.Client() in http.WithMiddleware, Kratos will print detailed request information every time an Http request is initiated.

  1. logger := log.DefaultLogger
  2. conn, err := http.NewClient(
  3. context.Background(),
  4. http.WithMiddleware(
  5. logging.Client(logger),
  6. ),
  7. http.WithEndpoint("127.0.0.1:8000"),
  8. )

The Logging middleware only prints trace_id in the server and does not collect data.

grpc-server

  1. // internal/server/grpc.go
  2. exporter, err := stdouttrace.New(stdouttrace.WithWriter(ioutil.Discard))
  3. if err != nil {
  4. fmt.Printf("creating stdout exporter: %v", err)
  5. panic(err)
  6. }
  7. tp := tracesdk.NewTracerProvider(
  8. tracesdk.WithBatcher(exporter),
  9. tracesdk.WithResource(resource.NewSchemaless(
  10. semconv.ServiceNameKey.String(Name)),
  11. )
  12. )
  13. var opts = []grpc.ServerOption{
  14. grpc.Middleware(
  15. tracing.Server(tracing.WithTracerProvider(tp)),
  16. ),
  17. }
  18. srv := grpc.NewServer(opts...)

Add the trace_id field to the output log

  1. // cmd/project_name/main.go
  2. logger := log.With(
  3. log.NewStdLogger(os.Stdout),
  4. "ts", log.DefaultTimestamp,
  5. "caller", log.DefaultCaller,
  6. "service.id", id,
  7. "service.name", Name,
  8. "service.version", Version,
  9. "trace_id", log.TraceID(),
  10. "span_id", log.SpanID(),
  11. )

Log trace_id

  1. log.WithContext(ctx).Errorf("Field created: %s", err)