github.com/zchee/zap-cloudlogging@v0.0.0-20220819025602-19b026d3900e/operation.go (about)

     1  // Copyright 2022 The zap-cloudlogging Authors
     2  // SPDX-License-Identifier: BSD-3-Clause
     3  
     4  package zapcloudlogging
     5  
     6  import (
     7  	"go.uber.org/zap"
     8  	"go.uber.org/zap/zapcore"
     9  	logpb "google.golang.org/genproto/googleapis/logging/v2"
    10  )
    11  
    12  const (
    13  	// OperationKey is the value of this field is also used by the Logs Explorer to group related log entries.
    14  	//
    15  	// operation field:
    16  	// - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.operation
    17  	// - https://cloud.google.com/logging/docs/structured-logging#special-payload-fields
    18  	OperationKey = "logging.googleapis.com/operation"
    19  )
    20  
    21  // operation is the payload of Cloud Logging operation field.
    22  type operation struct {
    23  	*logpb.LogEntryOperation
    24  }
    25  
    26  var _ zapcore.ObjectMarshaler = (*operation)(nil)
    27  
    28  // MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject.
    29  func (op operation) MarshalLogObject(enc zapcore.ObjectEncoder) error {
    30  	enc.AddString("id", op.GetId())
    31  	enc.AddString("producer", op.GetProducer())
    32  	enc.AddBool("first", op.GetFirst())
    33  	enc.AddBool("last", op.GetLast())
    34  
    35  	return nil
    36  }
    37  
    38  // Operation adds the Cloud Logging "operation" fields from args.
    39  //
    40  // operation: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntryOperation
    41  func Operation(id, producer string, first, last bool) zapcore.Field {
    42  	op := &operation{
    43  		LogEntryOperation: &logpb.LogEntryOperation{
    44  			Id:       id,
    45  			Producer: producer,
    46  			First:    first,
    47  			Last:     last,
    48  		},
    49  	}
    50  
    51  	return zap.Object(OperationKey, op)
    52  }
    53  
    54  // OperationStart is a convenience function for `Operation`.
    55  //
    56  // It should be called for the first operation log.
    57  func OperationStart(id, producer string) zapcore.Field {
    58  	return Operation(id, producer, true, false)
    59  }
    60  
    61  // OperationCont is a convenience function for `Operation`.
    62  //
    63  // It should be called for any non-start/end operation log.
    64  func OperationCont(id, producer string) zapcore.Field {
    65  	return Operation(id, producer, false, false)
    66  }
    67  
    68  // OperationEnd is a convenience function for `Operation`.
    69  //
    70  // It should be called for the last operation log.
    71  func OperationEnd(id, producer string) zapcore.Field {
    72  	return Operation(id, producer, false, true)
    73  }