sink.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. *
  3. * Copyright 2020 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package binarylog implementation binary logging as defined in
  19. // https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
  20. //
  21. // Notice: All APIs in this package are experimental.
  22. package binarylog
  23. import (
  24. "fmt"
  25. "os"
  26. binlogpb "google.golang.org/grpc/binarylog/grpc_binarylog_v1"
  27. iblog "google.golang.org/grpc/internal/binarylog"
  28. )
  29. // SetSink sets the destination for the binary log entries.
  30. //
  31. // NOTE: this function must only be called during initialization time (i.e. in
  32. // an init() function), and is not thread-safe.
  33. func SetSink(s Sink) {
  34. if iblog.DefaultSink != nil {
  35. iblog.DefaultSink.Close()
  36. }
  37. iblog.DefaultSink = s
  38. }
  39. // Sink represents the destination for the binary log entries.
  40. type Sink interface {
  41. // Write marshals the log entry and writes it to the destination. The format
  42. // is not specified, but should have sufficient information to rebuild the
  43. // entry. Some options are: proto bytes, or proto json.
  44. //
  45. // Note this function needs to be thread-safe.
  46. Write(*binlogpb.GrpcLogEntry) error
  47. // Close closes this sink and cleans up resources (e.g. the flushing
  48. // goroutine).
  49. Close() error
  50. }
  51. // NewTempFileSink creates a temp file and returns a Sink that writes to this
  52. // file.
  53. func NewTempFileSink() (Sink, error) {
  54. // Two other options to replace this function:
  55. // 1. take filename as input.
  56. // 2. export NewBufferedSink().
  57. tempFile, err := os.CreateTemp("/tmp", "grpcgo_binarylog_*.txt")
  58. if err != nil {
  59. return nil, fmt.Errorf("failed to create temp file: %v", err)
  60. }
  61. return iblog.NewBufferedSink(tempFile), nil
  62. }