istio
1// Copyright Istio Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package clog16
17import (18"fmt"19"io"20"os"21
22"istio.io/istio/pkg/log"23)
24
25// Logger provides optional log taps for console and test buffer outputs.
26type Logger interface {27LogAndPrint(v ...any)28LogAndError(v ...any)29LogAndFatal(a ...any)30LogAndPrintf(format string, a ...any)31LogAndErrorf(format string, a ...any)32LogAndFatalf(format string, a ...any)33Print(s string)34PrintErr(s string)35}
36
37// ConsoleLogger is the struct used for mesh command
38type ConsoleLogger struct {39stdOut io.Writer40stdErr io.Writer41scope *log.Scope42}
43
44// NewConsoleLogger creates a new logger and returns a pointer to it.
45// stdOut and stdErr can be used to capture output for testing. If scope is nil, the default scope is used.
46func NewConsoleLogger(stdOut, stdErr io.Writer, scope *log.Scope) *ConsoleLogger {47s := scope48if s == nil {49s = log.RegisterScope(log.DefaultScopeName, log.DefaultScopeName)50}51return &ConsoleLogger{52stdOut: stdOut,53stdErr: stdErr,54scope: s,55}56}
57
58// NewDefaultLogger creates a new logger that outputs to stdout/stderr at default scope.
59func NewDefaultLogger() *ConsoleLogger {60return NewConsoleLogger(os.Stdout, os.Stderr, nil)61}
62
63func (l *ConsoleLogger) LogAndPrint(v ...any) {64if len(v) == 0 {65return66}67s := fmt.Sprint(v...)68l.Print(s + "\n")69l.scope.Infof(s)70}
71
72func (l *ConsoleLogger) LogAndError(v ...any) {73if len(v) == 0 {74return75}76s := fmt.Sprint(v...)77l.PrintErr(s + "\n")78l.scope.Infof(s)79}
80
81func (l *ConsoleLogger) LogAndFatal(a ...any) {82l.LogAndError(a...)83os.Exit(-1)84}
85
86func (l *ConsoleLogger) LogAndPrintf(format string, a ...any) {87s := fmt.Sprintf(format, a...)88l.Print(s + "\n")89l.scope.Infof(s)90}
91
92func (l *ConsoleLogger) LogAndErrorf(format string, a ...any) {93s := fmt.Sprintf(format, a...)94l.PrintErr(s + "\n")95l.scope.Infof(s)96}
97
98func (l *ConsoleLogger) LogAndFatalf(format string, a ...any) {99l.LogAndErrorf(format, a...)100os.Exit(-1)101}
102
103func (l *ConsoleLogger) Print(s string) {104_, _ = l.stdOut.Write([]byte(s))105}
106
107func (l *ConsoleLogger) PrintErr(s string) {108_, _ = l.stdErr.Write([]byte(s))109}
110