github.com/openebs/node-disk-manager@v1.9.1-0.20230225014141-4531f06ffa1e/pkg/logs/logs.go (about)

     1  /*
     2  Copyright 2018 The OpenEBS Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package logs
    18  
    19  import (
    20  	"flag"
    21  	"log"
    22  	"time"
    23  
    24  	"github.com/spf13/pflag"
    25  	"k8s.io/apimachinery/pkg/util/wait"
    26  	"k8s.io/klog/v2"
    27  )
    28  
    29  var logFlushFreq = pflag.Duration("log-flush-frequency", 5*time.Second, "Maximum number of seconds between log flushes")
    30  
    31  // TODO(thockin): This is temporary until we agree on log dirs and put those into each cmd.
    32  func init() {
    33  	err := flag.Set("logtostderr", "true")
    34  	if err != nil {
    35  		klog.Errorf("unable to set flag, Error: %v", err)
    36  	}
    37  }
    38  
    39  // KlogWriter serves as a bridge between the standard log package and the klog package.
    40  type KlogWriter struct{}
    41  
    42  // Write implements the io.Writer interface.
    43  func (writer KlogWriter) Write(data []byte) (n int, err error) {
    44  	klog.Info(string(data))
    45  	return len(data), nil
    46  }
    47  
    48  // InitLogs initializes logs the way we want for kubernetes.
    49  func InitLogs() {
    50  	log.SetOutput(KlogWriter{})
    51  	log.SetFlags(0)
    52  	// The default glog flush interval is 30 seconds, which is frighteningly long.
    53  	go wait.Until(klog.Flush, *logFlushFreq, wait.NeverStop)
    54  }
    55  
    56  // FlushLogs flushes logs immediately.
    57  func FlushLogs() {
    58  	klog.Flush()
    59  }
    60  
    61  // NewLogger creates a new log.Logger which sends logs to klog.Info.
    62  func NewLogger(prefix string) *log.Logger {
    63  	return log.New(KlogWriter{}, prefix, 0)
    64  }