...

Source file src/sigs.k8s.io/release-utils/log/log.go

Documentation: sigs.k8s.io/release-utils/log

     1  /*
     2  Copyright 2020 The Kubernetes 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 log
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"strings"
    24  
    25  	"github.com/sirupsen/logrus"
    26  
    27  	"sigs.k8s.io/release-utils/command"
    28  )
    29  
    30  // SetupGlobalLogger uses to provided log level string and applies it globally.
    31  func SetupGlobalLogger(level string) error {
    32  	logrus.SetFormatter(&logrus.TextFormatter{
    33  		DisableTimestamp: true,
    34  		ForceColors:      false,
    35  	})
    36  
    37  	lvl, err := logrus.ParseLevel(level)
    38  	if err != nil {
    39  		return fmt.Errorf("setting log level to %s: %w", level, err)
    40  	}
    41  	logrus.SetLevel(lvl)
    42  	if lvl >= logrus.DebugLevel {
    43  		logrus.Debug("Setting commands globally into verbose mode")
    44  		command.SetGlobalVerbose(true)
    45  	}
    46  	logrus.AddHook(NewFilenameHook())
    47  	logrus.Debugf("Using log level %q", lvl)
    48  	return nil
    49  }
    50  
    51  // ToFile adds a file destination to the global logger.
    52  func ToFile(fileName string) error {
    53  	file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0o755)
    54  	if err != nil {
    55  		return fmt.Errorf("open log file: %w", err)
    56  	}
    57  
    58  	writer := io.MultiWriter(logrus.StandardLogger().Out, file)
    59  	logrus.SetOutput(writer)
    60  
    61  	return nil
    62  }
    63  
    64  // LevelNames returns a comma separated list of available levels.
    65  func LevelNames() string {
    66  	levels := []string{}
    67  	for _, level := range logrus.AllLevels {
    68  		levels = append(levels, fmt.Sprintf("'%s'", level.String()))
    69  	}
    70  	return strings.Join(levels, ", ")
    71  }
    72  

View as plain text