slogs

package
v0.0.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2024 License: Apache-2.0 Imports: 4 Imported by: 7

README

slogs

This is a wrapper around the stdlib Golang slog package that just creates a slog logger in some standard way, with a configurable log level.

Slog was introduced in Go 1.21, so that is the minimum required Go version to use this module.

Usage

package main

import "github.com/chia-network/go-modules/pkg/slogs"

func main() {
	// Init the logger with a log-level string (debug, info, warn, error)
	// defaults to "info" if empty or unsupported string 
	slogs.Init("info")
	
	// Logs a hello world message at the info level
	slogs.Logr.Info("hello world")
	
	// Logs an error message at the error level 
	slogs.Logr.Error("we received an error")
}

In a Cobra/Viper CLI app this might look more like:

package cmd

import (
	"log"
	
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/chia-network/go-modules/pkg/slogs"
)

var rootCmd = &cobra.Command{
	Use:   "cmd",
	Short: "Short help message for cmd",

	Run: func(cmd *cobra.Command, args []string) {
		// Init logger
		slogs.Init(viper.GetString("log-level"))

		// Application logic below
	},
}

func Execute() {
	cobra.CheckErr(rootCmd.Execute())
}

func init() {
	rootCmd.PersistentFlags().String("log-level", "info", "The log-level for the application, can be one of info, warn, error, debug.")
	err := viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
	if err != nil {
		log.Fatalln(err.Error()) // Have to log with standard logger until the slog logger is initialized
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init

func Init(level string)

Init custom init function that accepts the log level for the application and initializes a stdout slog logger

Types

type Logger

type Logger struct {
	*slog.Logger
}

Logger is a wrapper around the slog logger struct so we can have a type that is owned by this scope to create additional wrapper functions around

var Logr Logger

Logr is a custom text logger from the stdlib slog package

func (Logger) Fatal

func (l Logger) Fatal(msg string, args ...any)

Fatal is a wrapper around the standard slog Error function that exits 1 after it is called. Similar to the stdlib log.Fatal function

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL