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

     1  // Copyright 2022 The zap-cloudlogging Authors
     2  // SPDX-License-Identifier: BSD-3-Clause
     3  
     4  package zapcloudlogging
     5  
     6  import (
     7  	"sync"
     8  
     9  	"go.uber.org/zap"
    10  	"go.uber.org/zap/zapcore"
    11  )
    12  
    13  const (
    14  	// LabelsKeys is the value of this field must be a structured record. For more information.
    15  	//
    16  	// labels field:
    17  	// - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.labels
    18  	LabelsKey = "logging.googleapis.com/labels"
    19  )
    20  
    21  // Label adds the Cloud Logging "labels" field from key and val.
    22  //
    23  // Cloud Logging truncates label keys that exceed 512 B and label values that exceed 64 KB upon their associated log entry being written.
    24  // The truncation is indicated by an ellipsis at the end of the character string.
    25  func Label(key, val string) zapcore.Field {
    26  	return zap.String("labels."+key, val)
    27  }
    28  
    29  // labelMap map of labels.
    30  type labelMap struct {
    31  	m sync.Map
    32  }
    33  
    34  // Add adds the val for a key.
    35  func (l *labelMap) Add(key, val string) {
    36  	l.m.Store(key, val)
    37  }
    38  
    39  // Delete deletes the value for a key.
    40  func (l *labelMap) Delete(key string) {
    41  	l.m.Delete(key)
    42  }
    43  
    44  // MarshalLogObject implements zapcore.ObjectMarshaler.
    45  func (l *labelMap) MarshalLogObject(enc zapcore.ObjectEncoder) error {
    46  	l.m.Range(func(key, val any) bool {
    47  		enc.AddString(key.(string), val.(string))
    48  
    49  		return true
    50  	})
    51  
    52  	return nil
    53  }
    54  
    55  // Label adds the Cloud Logging "labels" field from keyvals.
    56  func Labels(keyvals ...string) zapcore.Field {
    57  	if len(keyvals)%2 != 0 {
    58  		panic("keyval length should be powers of two")
    59  	}
    60  
    61  	fields := new(labelMap)
    62  	for i := 0; i < len(keyvals)/2; i++ {
    63  		key := keyvals[i]
    64  		val := keyvals[i+1]
    65  		fields.Add(key, val)
    66  	}
    67  
    68  	return zap.Object(LabelsKey, fields)
    69  }