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
19package grpclog
20
21import (
22	"fmt"
23)
24
25// PrefixLogger does logging with a prefix.
26//
27// Logging method on a nil logs without any prefix.
28type PrefixLogger struct {
29	logger DepthLoggerV2
30	prefix string
31}
32
33// Infof does info logging.
34func (pl *PrefixLogger) Infof(format string, args ...interface{}) {
35	if pl != nil {
36		// Handle nil, so the tests can pass in a nil logger.
37		format = pl.prefix + format
38		pl.logger.InfoDepth(1, fmt.Sprintf(format, args...))
39		return
40	}
41	InfoDepth(1, fmt.Sprintf(format, args...))
42}
43
44// Warningf does warning logging.
45func (pl *PrefixLogger) Warningf(format string, args ...interface{}) {
46	if pl != nil {
47		format = pl.prefix + format
48		pl.logger.WarningDepth(1, fmt.Sprintf(format, args...))
49		return
50	}
51	WarningDepth(1, fmt.Sprintf(format, args...))
52}
53
54// Errorf does error logging.
55func (pl *PrefixLogger) Errorf(format string, args ...interface{}) {
56	if pl != nil {
57		format = pl.prefix + format
58		pl.logger.ErrorDepth(1, fmt.Sprintf(format, args...))
59		return
60	}
61	ErrorDepth(1, fmt.Sprintf(format, args...))
62}
63
64// Debugf does info logging at verbose level 2.
65func (pl *PrefixLogger) Debugf(format string, args ...interface{}) {
66	if !Logger.V(2) {
67		return
68	}
69	if pl != nil {
70		// Handle nil, so the tests can pass in a nil logger.
71		format = pl.prefix + format
72		pl.logger.InfoDepth(1, fmt.Sprintf(format, args...))
73		return
74	}
75	InfoDepth(1, fmt.Sprintf(format, args...))
76}
77
78// NewPrefixLogger creates a prefix logger with the given prefix.
79func NewPrefixLogger(logger DepthLoggerV2, prefix string) *PrefixLogger {
80	return &PrefixLogger{logger: logger, prefix: prefix}
81}
82