google.golang.org/grpc@v1.72.2/internal/grpclog/prefix_logger.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 grpclog provides logging functionality for internal gRPC packages,
    20  // outside of the functionality provided by the external `grpclog` package.
    21  package grpclog
    22  
    23  import (
    24  	"fmt"
    25  
    26  	"google.golang.org/grpc/grpclog"
    27  )
    28  
    29  // PrefixLogger does logging with a prefix.
    30  //
    31  // Logging method on a nil logs without any prefix.
    32  type PrefixLogger struct {
    33  	logger grpclog.DepthLoggerV2
    34  	prefix string
    35  }
    36  
    37  // Infof does info logging.
    38  func (pl *PrefixLogger) Infof(format string, args ...any) {
    39  	if pl != nil {
    40  		// Handle nil, so the tests can pass in a nil logger.
    41  		format = pl.prefix + format
    42  		pl.logger.InfoDepth(1, fmt.Sprintf(format, args...))
    43  		return
    44  	}
    45  	grpclog.InfoDepth(1, fmt.Sprintf(format, args...))
    46  }
    47  
    48  // Warningf does warning logging.
    49  func (pl *PrefixLogger) Warningf(format string, args ...any) {
    50  	if pl != nil {
    51  		format = pl.prefix + format
    52  		pl.logger.WarningDepth(1, fmt.Sprintf(format, args...))
    53  		return
    54  	}
    55  	grpclog.WarningDepth(1, fmt.Sprintf(format, args...))
    56  }
    57  
    58  // Errorf does error logging.
    59  func (pl *PrefixLogger) Errorf(format string, args ...any) {
    60  	if pl != nil {
    61  		format = pl.prefix + format
    62  		pl.logger.ErrorDepth(1, fmt.Sprintf(format, args...))
    63  		return
    64  	}
    65  	grpclog.ErrorDepth(1, fmt.Sprintf(format, args...))
    66  }
    67  
    68  // V reports whether verbosity level l is at least the requested verbose level.
    69  func (pl *PrefixLogger) V(l int) bool {
    70  	if pl != nil {
    71  		return pl.logger.V(l)
    72  	}
    73  	return true
    74  }
    75  
    76  // NewPrefixLogger creates a prefix logger with the given prefix.
    77  func NewPrefixLogger(logger grpclog.DepthLoggerV2, prefix string) *PrefixLogger {
    78  	return &PrefixLogger{logger: logger, prefix: prefix}
    79  }