github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/grpc/binarylog/sink.go (about)

     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  
    19  // Package binarylog implementation binary logging as defined in
    20  // https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
    21  //
    22  // Notice: All APIs in this package are experimental.
    23  package binarylog
    24  
    25  import (
    26  	"fmt"
    27  	"io/ioutil"
    28  
    29  	pb "github.com/hxx258456/ccgo/grpc/binarylog/grpc_binarylog_v1"
    30  	iblog "github.com/hxx258456/ccgo/grpc/internal/binarylog"
    31  )
    32  
    33  // SetSink sets the destination for the binary log entries.
    34  //
    35  // NOTE: this function must only be called during initialization time (i.e. in
    36  // an init() function), and is not thread-safe.
    37  func SetSink(s Sink) {
    38  	if iblog.DefaultSink != nil {
    39  		iblog.DefaultSink.Close()
    40  	}
    41  	iblog.DefaultSink = s
    42  }
    43  
    44  // Sink represents the destination for the binary log entries.
    45  type Sink interface {
    46  	// Write marshals the log entry and writes it to the destination. The format
    47  	// is not specified, but should have sufficient information to rebuild the
    48  	// entry. Some options are: proto bytes, or proto json.
    49  	//
    50  	// Note this function needs to be thread-safe.
    51  	Write(*pb.GrpcLogEntry) error
    52  	// Close closes this sink and cleans up resources (e.g. the flushing
    53  	// goroutine).
    54  	Close() error
    55  }
    56  
    57  // NewTempFileSink creates a temp file and returns a Sink that writes to this
    58  // file.
    59  func NewTempFileSink() (Sink, error) {
    60  	// Two other options to replace this function:
    61  	// 1. take filename as input.
    62  	// 2. export NewBufferedSink().
    63  	tempFile, err := ioutil.TempFile("/tmp", "grpcgo_binarylog_*.txt")
    64  	if err != nil {
    65  		return nil, fmt.Errorf("failed to create temp file: %v", err)
    66  	}
    67  	return iblog.NewBufferedSink(tempFile), nil
    68  }