github.com/9elements/firmware-action/action@v0.0.0-20240514065043-044ed91c9ed8/logging/logging.go (about)

     1  // SPDX-License-Identifier: MIT
     2  
     3  // Package logging for dealing with logging, log settings and log format
     4  package logging
     5  
     6  import (
     7  	"log/slog"
     8  	"os"
     9  	"path/filepath"
    10  	"runtime"
    11  )
    12  
    13  // ThisShouldNotHappenMessage contains a string which should be used in error message where the error justifies
    14  // opening an issue in issue tracker
    15  const ThisShouldNotHappenMessage = "this should not happen, please open an issue in issue tracker at https://github.com/9elements/firmware-action/issues"
    16  
    17  // InitLogger is used to initialize logger
    18  func InitLogger(level slog.Level, opts ...PrettyHandlerOption) {
    19  	// Deal with log level
    20  	//   LevelDebug Level = -4
    21  	//   LevelInfo  Level = 0
    22  	//   LevelWarn  Level = 4
    23  	//   LevelError Level = 8
    24  	_ = slog.SetLogLoggerLevel(level)
    25  
    26  	options := []PrettyHandlerOption{WithLevel(level)}
    27  	options = append(options, opts[:]...)
    28  	pHandler := NewPrettyHandler(
    29  		os.Stdout,
    30  		options[:]...,
    31  	)
    32  
    33  	slog.SetDefault(slog.New(pHandler))
    34  }
    35  
    36  // TrimNameFunction just trims the name
    37  func TrimNameFunction(pc uintptr) string {
    38  	// 'runtime.FuncForPC(pc).Name()' is nice and all, but it will return this monstrosity:
    39  	//   github.com/9elements/firmware-action/action/<package>.<func>...
    40  	// So this function is just to trim it down
    41  	// Usage:
    42  	//   pc, _, _, _ := runtime.Caller(0)
    43  	//   name := logging.TrimFunctionName(pc)
    44  	return filepath.Base(runtime.FuncForPC(pc).Name())
    45  }