github.com/verrazzano/verrazzano@v1.7.1/tests/e2e/pkg/logging.go (about)

     1  // Copyright (c) 2020, 2021, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package pkg
     5  
     6  import (
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/onsi/ginkgo/v2"
    11  )
    12  
    13  // LogLevel is the logging level used to control log output
    14  type LogLevel int
    15  
    16  const (
    17  	// Error level designates error events that might still allow the application to continue running
    18  	Error LogLevel = 1
    19  	// Info level designates informational messages that highlight the progress of the application at coarse-grained level
    20  	Info LogLevel = 4
    21  	// Debug level designates fine-grained informational events that are most useful to debug an application
    22  	Debug LogLevel = 7
    23  )
    24  
    25  // the global log level, i.e. the level of logging that was requested by
    26  // the caller (by setting the LOG_LEVEL environment variable).
    27  var globalLogLevel LogLevel
    28  
    29  // Log prints out a log message in a standard format and filters out messages
    30  // based on the global log level
    31  func Log(level LogLevel, message string) {
    32  	// if the global log level has not been set yet, then set it
    33  	if globalLogLevel == 0 {
    34  		level, _ := os.LookupEnv("LOG_LEVEL")
    35  		switch level {
    36  		case "ERROR":
    37  			globalLogLevel = Error
    38  		case "INFO":
    39  			globalLogLevel = Info
    40  		case "DEBUG":
    41  			globalLogLevel = Debug
    42  		default:
    43  			globalLogLevel = Info
    44  		}
    45  	}
    46  
    47  	// only print messages at or below the global log level
    48  	if level <= globalLogLevel {
    49  		var levelHeader string
    50  		switch level {
    51  		case Error:
    52  			levelHeader = "[ERROR]"
    53  		case Info:
    54  			levelHeader = "[INFO]"
    55  		case Debug:
    56  			levelHeader = "[DEBUG]"
    57  		default:
    58  			levelHeader = "[INFO]"
    59  		}
    60  		ginkgo.GinkgoWriter.Write([]byte(levelHeader + " " + time.Now().Format("2020-01-02 15:04:05.000000") + " " + message + "\n"))
    61  	}
    62  }
    63  
    64  // CreateLogFile creates a file with the given name (or truncates the file if it already exists)
    65  // and writes the given content string to the file.
    66  func CreateLogFile(filename string, content string) error {
    67  	// create out output file
    68  	f, err := os.Create(filename + ".log")
    69  	if err != nil {
    70  		return err
    71  	}
    72  	defer f.Close()
    73  
    74  	f.WriteString(content)
    75  	f.Sync()
    76  	return nil
    77  }