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.

Use in the project

grpc-server internal/server/grpc.go

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

Add the trace_id field to the output log, cmd/project_name/main.go.

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

Log trace_id

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