logging

package
v2.2.6 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: MIT Imports: 14 Imported by: 1

README

goutils/v2/logging

The logging package is a collection of utility functions designed to simplify common logging tasks.


Table of contents


Functions

ColorLogger.Debug(...interface{})
Debug(...interface{})

Debug for ColorLogger logs the provided arguments as a debug line in the specified color. The arguments are handled in the manner of fmt.Println.


ColorLogger.Debugf(string, ...interface{})
Debugf(string, ...interface{})

Debugf for ColorLogger logs the provided formatted string as a debug line in the specified color. The format and arguments are handled in the manner of fmt.Printf.


ColorLogger.Error(...interface{})
Error(...interface{})

Error for ColorLogger logs the provided arguments as an error line in the specified color. The arguments are handled in the manner of fmt.Println.


ColorLogger.Errorf(string, ...interface{})
Errorf(string, ...interface{})

Errorf for ColorLogger logs the provided formatted string as an error line in the specified color. The format and arguments are handled in the manner of fmt.Printf.


ColorLogger.Printf(string, ...interface{})
Printf(string, ...interface{})

Printf for ColorLogger logs the provided formatted string in the specified color. The format and arguments are handled in the manner of fmt.Printf.


ColorLogger.Println(...interface{})
Println(...interface{})

Println for ColorLogger logs the provided arguments as a line in the specified color. The arguments are handled in the manner of fmt.Println.


ColorLogger.Warn(...interface{})
Warn(...interface{})

Warn for ColorLogger logs the provided arguments as a warning line in the specified color. The arguments are handled in the manner of fmt.Println.


ColorLogger.Warnf(string, ...interface{})
Warnf(string, ...interface{})

Warnf for ColorLogger logs the provided formatted string as a warning line in the specified color. The format and arguments are handled in the manner of fmt.Printf.


DetermineLogLevel(string)
DetermineLogLevel(string) slog.Level

DetermineLogLevel determines the log level from a given string.

Parameters:

levelStr: A string representing the log level.

Returns:

slog.Level: The corresponding slog.Level for the given log level string.


InitLogging(*LogConfig)
InitLogging(*LogConfig) Logger, error

InitLogging is a convenience function that combines the CreateLogFile and ConfigureLogger functions into one call. It is useful for quickly setting up logging to disk.

Parameters:

fs: An afero.Fs instance for filesystem operations, allows mocking in tests. logPath: The path to the log file. level: The logging level. outputType: The output type of the logger (PlainOutput or ColorOutput). logToDisk: A boolean indicating whether to log to disk or not.

Returns:

Logger: A configured Logger object. error: An error if any issue occurs during initialization.


L()
L() Logger

L returns the global logger instance for use in logging operations.

Returns:

Logger: The global Logger instance.


LogAndReturnError(Logger, string)
LogAndReturnError(Logger, string) error

LogAndReturnError logs the provided error message using the given logger and returns the error.

This utility function is helpful for scenarios where an error needs to be both logged and returned. It simplifies the code by combining these two actions into one call.

Parameters:

logger: The Logger instance used for logging the error. errMsg: The error message to log and return.

Returns:

error: The error created from the errMsg, after it has been logged.


LogConfig.ConfigureLogger()
ConfigureLogger() Logger, error

ConfigureLogger sets up a logger based on the provided logging level, file path, and output type. It supports both colorized and plain text logging output, selectable via the OutputType parameter. The logger writes log entries to both a file and standard output.

Parameters:

level: Logging level as a slog.Level. path: Path to the log file. outputType: Type of log output, either ColorOutput or PlainOutput.

Returns:

Logger: Configured Logger object based on provided parameters. error: An error, if an issue occurs while setting up the logger.


LogConfig.CreateLogFile()
CreateLogFile() error

CreateLogFile creates a log file in a 'logs' subdirectory of the specified directory. The log file's name is the provided log name with the extension '.log'.

Parameters:

fs: An afero.Fs instance to mock filesystem for testing. logDir: A string for the directory where 'logs' subdirectory and log file should be created. logName: A string for the name of the log file to be created.

Returns:

LogConfig: A LogConfig struct with information about the log file, including its directory, file pointer, file name, and path. error: An error, if an issue occurs while creating the directory or the log file.


NewColorLogger(LogConfig, color.Attribute, *slog.Logger)
NewColorLogger(LogConfig, color.Attribute, *slog.Logger) *ColorLogger, error

NewColorLogger creates a new ColorLogger instance with the specified LogConfig, color attribute, and slog.Logger.

Parameters:

cfg: LogConfig object containing information about the log file. colorAttr: A color attribute for output styling. logger: The slog Logger instance used for logging operations.

Returns:

*ColorLogger: A new instance of ColorLogger. error: An error if any issue occurs during initialization.


NewPlainLogger(LogConfig, *slog.Logger)
NewPlainLogger(LogConfig, *slog.Logger) *PlainLogger, error

NewPlainLogger creates a new PlainLogger instance with the specified LogConfig and slog.Logger.

Parameters:

cfg: LogConfig object containing information about the log file. logger: The slog Logger instance used for logging operations.

Returns:

*PlainLogger: A new instance of PlainLogger. error: An error if any issue occurs during initialization.


NewPrettyHandler(io.Writer, PrettyHandlerOptions)
NewPrettyHandler(io.Writer, PrettyHandlerOptions) *PrettyHandler

NewPrettyHandler creates a new PrettyHandler with specified output writer and options. It configures the PrettyHandler for handling log messages with optional colorization and structured formatting.

Parameters:

out: Output writer where log messages will be written. opts: PrettyHandlerOptions for configuring the handler.

Returns:

*PrettyHandler: A new instance of PrettyHandler.


PlainLogger.Debug(...interface{})
Debug(...interface{})

Debug for PlainLogger logs the provided arguments as a debug line using slog library. The arguments are converted to a string using fmt.Sprint.


PlainLogger.Debugf(string, ...interface{})
Debugf(string, ...interface{})

Debugf for PlainLogger logs the provided formatted string as a debug line using slog library. The format and arguments are handled in the manner of fmt.Printf.


PlainLogger.Error(...interface{})
Error(...interface{})

Error for PlainLogger logs the provided arguments as an error line using slog library. The arguments are converted to a string using fmt.Sprint.


PlainLogger.Errorf(string, ...interface{})
Errorf(string, ...interface{})

Errorf for PlainLogger logs the provided formatted string as an error line using slog library. The format and arguments are handled in the manner of fmt.Printf.


PlainLogger.Printf(string, ...interface{})
Printf(string, ...interface{})

Printf for PlainLogger logs the provided formatted string using slog library. The format and arguments are handled in the manner of fmt.Printf.


PlainLogger.Println(...interface{})
Println(...interface{})

Println for PlainLogger logs the provided arguments as a line using slog library. The arguments are converted to a string using fmt.Sprint. PlainLogger.go


PlainLogger.Warn(...interface{})
Warn(...interface{})

Warn for PlainLogger logs the provided arguments as a warning line using slog library. The arguments are converted to a string using fmt.Sprint.


PlainLogger.Warnf(string, ...interface{})
Warnf(string, ...interface{})

Warnf for PlainLogger logs the provided formatted string as a warning line using slog library. The format and arguments are handled in the manner of fmt.Printf.


PrettyHandler.Handle(context.Context, slog.Record)
Handle(context.Context, slog.Record) error

Handle processes and outputs a log record using the PrettyHandler. It supports both colorized and non-colorized log messages and can output in JSON format if not writing to a terminal.

Parameters:

ctx: Context for the log record. r: The log record containing log data.

Returns:

error: An error if any issue occurs during log handling.


Installation

To use the goutils/v2/logging package, you first need to install it. Follow the steps below to install via go get.

go get github.com/l50/goutils/v2/logging

Usage

After installation, you can import the package in your Go project using the following import statement:

import "github.com/l50/goutils/v2/logging"

Tests

To ensure the package is working correctly, run the following command to execute the tests for goutils/v2/logging:

go test -v

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.


License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DetermineLogLevel added in v2.2.3

func DetermineLogLevel(levelStr string) slog.Level

DetermineLogLevel determines the log level from a given string.

**Parameters:**

levelStr: A string representing the log level.

**Returns:**

slog.Level: The corresponding slog.Level for the given log level string.

func LogAndReturnError added in v2.2.1

func LogAndReturnError(logger Logger, errMsg string) error

LogAndReturnError logs the provided error message using the given logger and returns the error.

This utility function is helpful for scenarios where an error needs to be both logged and returned. It simplifies the code by combining these two actions into one call.

**Parameters:**

logger: The Logger instance used for logging the error. errMsg: The error message to log and return.

**Returns:**

error: The error created from the errMsg, after it has been logged.

Types

type ColorLogger added in v2.1.8

type ColorLogger struct {
	Cfg            LogConfig
	ColorAttribute color.Attribute
	Logger         *slog.Logger
}

ColorLogger is a logger that outputs messages in a specified color. It enhances readability by color-coding log messages based on their severity or purpose.

**Attributes:**

Info: LogConfig object containing information about the log file. ColorAttribute: A color attribute for output styling. Logger: The slog Logger instance used for logging operations.

func NewColorLogger added in v2.2.1

func NewColorLogger(cfg LogConfig, colorAttr color.Attribute, logger *slog.Logger) (*ColorLogger, error)

NewColorLogger creates a new ColorLogger instance with the specified LogConfig, color attribute, and slog.Logger.

**Parameters:**

cfg: LogConfig object containing information about the log file. colorAttr: A color attribute for output styling. logger: The slog Logger instance used for logging operations.

**Returns:**

*ColorLogger: A new instance of ColorLogger. error: An error if any issue occurs during initialization.

func (*ColorLogger) Debug added in v2.1.8

func (l *ColorLogger) Debug(v ...interface{})

Debug for ColorLogger logs the provided arguments as a debug line in the specified color. The arguments are handled in the manner of fmt.Println.

func (*ColorLogger) Debugf added in v2.1.8

func (l *ColorLogger) Debugf(format string, v ...interface{})

Debugf for ColorLogger logs the provided formatted string as a debug line in the specified color. The format and arguments are handled in the manner of fmt.Printf.

func (*ColorLogger) Error added in v2.1.8

func (l *ColorLogger) Error(v ...interface{})

Error for ColorLogger logs the provided arguments as an error line in the specified color. The arguments are handled in the manner of fmt.Println.

func (*ColorLogger) Errorf added in v2.1.8

func (l *ColorLogger) Errorf(format string, v ...interface{})

Errorf for ColorLogger logs the provided formatted string as an error line in the specified color. The format and arguments are handled in the manner of fmt.Printf.

func (*ColorLogger) Printf added in v2.1.8

func (l *ColorLogger) Printf(format string, v ...interface{})

Printf for ColorLogger logs the provided formatted string in the specified color. The format and arguments are handled in the manner of fmt.Printf.

func (*ColorLogger) Println added in v2.1.8

func (l *ColorLogger) Println(v ...interface{})

Println for ColorLogger logs the provided arguments as a line in the specified color. The arguments are handled in the manner of fmt.Println.

func (*ColorLogger) Warn added in v2.2.3

func (l *ColorLogger) Warn(v ...interface{})

Warn for ColorLogger logs the provided arguments as a warning line in the specified color. The arguments are handled in the manner of fmt.Println.

func (*ColorLogger) Warnf added in v2.2.3

func (l *ColorLogger) Warnf(format string, v ...interface{})

Warnf for ColorLogger logs the provided formatted string as a warning line in the specified color. The format and arguments are handled in the manner of fmt.Printf.

type LogConfig added in v2.2.1

type LogConfig struct {
	Fs         afero.Fs
	LogPath    string
	Level      slog.Level
	OutputType OutputType
	LogToDisk  bool
}

LogConfig represents parameters used to manage logging throughout a program.

**Attributes:**

Fs: An afero.Fs object representing the file system. Path: A string representing the full path to the log file. Level: A slog.Level object representing the logging level. LogToDisk: A boolean representing whether or not to log to disk.

func (*LogConfig) ConfigureLogger added in v2.2.1

func (cfg *LogConfig) ConfigureLogger() (Logger, error)

ConfigureLogger sets up a logger based on the provided logging level, file path, and output type. It supports both colorized and plain text logging output, selectable via the OutputType parameter. The logger writes log entries to both a file and standard output.

**Parameters:**

level: Logging level as a slog.Level. path: Path to the log file. outputType: Type of log output, either ColorOutput or PlainOutput.

**Returns:**

Logger: Configured Logger object based on provided parameters. error: An error, if an issue occurs while setting up the logger.

Example
package main

import (
	"fmt"
	"log/slog"
	"path/filepath"

	"github.com/l50/goutils/v2/logging"
	"github.com/spf13/afero"
)

func plainLoggerExample() {
	cfg := logging.LogConfig{
		Fs:         afero.NewOsFs(),
		LogPath:    filepath.Join("/tmp", "test.log"),
		Level:      slog.LevelDebug,
		OutputType: logging.PlainOutput,
		LogToDisk:  true,
	}

	logger, err := logging.InitLogging(&cfg)
	if err != nil {
		fmt.Printf("Failed to configure logger: %v", err)
		return
	}

	logger.Println("This is a log message")
	logger.Error("This is an error log message")
	logger.Errorf("This is a formatted error log message: %s", "Error details")

	fmt.Println("Logger configured successfully.")
}

func colorLoggerExample() {
	cfg := logging.LogConfig{
		Fs:         afero.NewOsFs(),
		LogPath:    filepath.Join("/tmp", "test.log"),
		Level:      slog.LevelDebug,
		OutputType: logging.ColorOutput,
		LogToDisk:  true,
	}

	logger, err := logging.InitLogging(&cfg)
	if err != nil {
		fmt.Printf("Failed to configure logger: %v", err)
		return
	}

	logger.Println("This is a log message")
	logger.Error("This is an error log message")
	logger.Errorf("This is a formatted error log message: %s", "Error details")

	fmt.Println("Logger configured successfully.")
}

func main() {
	plainLoggerExample()
	colorLoggerExample()
}
Output:

func (*LogConfig) CreateLogFile added in v2.2.1

func (cfg *LogConfig) CreateLogFile() error

CreateLogFile creates a log file in a 'logs' subdirectory of the specified directory. The log file's name is the provided log name with the extension '.log'.

**Parameters:**

fs: An afero.Fs instance to mock filesystem for testing. logDir: A string for the directory where 'logs' subdirectory and log file should be created. logName: A string for the name of the log file to be created.

**Returns:**

LogConfig: A LogConfig struct with information about the log file, including its directory, file pointer, file name, and path. error: An error, if an issue occurs while creating the directory or the log file.

Example
package main

import (
	"fmt"
	"log/slog"
	"path/filepath"

	"github.com/l50/goutils/v2/logging"
	"github.com/spf13/afero"
)

func main() {
	cfg := logging.LogConfig{
		Fs:         afero.NewOsFs(),
		LogPath:    filepath.Join("/tmp", "test.log"),
		Level:      slog.LevelDebug,
		OutputType: logging.ColorOutput,
		LogToDisk:  true,
	}

	fmt.Println("Creating log file...")
	if err := cfg.CreateLogFile(); err != nil {
		fmt.Printf("Failed to create log file: %v", err)
		return
	}

	fmt.Printf("Log file created at: %s", cfg.LogPath)

	if err := cfg.Fs.Remove(cfg.LogPath); err != nil {
		fmt.Printf("Failed to clean up: %v", err)
	}
}
Output:

type Logger added in v2.0.6

type Logger interface {
	Println(v ...interface{})
	Printf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
}

Logger is an interface that defines methods for a generic logging system. It supports basic logging operations like printing, formatted printing, error logging, and debug logging.

**Methods:**

Println: Outputs a line with the given arguments. Printf: Outputs a formatted string. Error: Logs an error message. Errorf: Logs a formatted error message. Debug: Logs a debug message. Debugf: Logs a formatted debug message. Warn: Logs a warning message. Warnf: Logs a formatted warning message.

var GlobalLogger Logger

GlobalLogger is a global variable that holds the instance of the logger.

func InitLogging added in v2.2.0

func InitLogging(cfg *LogConfig) (Logger, error)

InitLogging is a convenience function that combines the CreateLogFile and ConfigureLogger functions into one call. It is useful for quickly setting up logging to disk.

**Parameters:**

fs: An afero.Fs instance for filesystem operations, allows mocking in tests. logPath: The path to the log file. level: The logging level. outputType: The output type of the logger (PlainOutput or ColorOutput). logToDisk: A boolean indicating whether to log to disk or not.

**Returns:**

Logger: A configured Logger object. error: An error if any issue occurs during initialization.

Example
package main

import (
	"fmt"
	"log/slog"
	"path/filepath"

	"github.com/l50/goutils/v2/logging"
	"github.com/spf13/afero"
)

func main() {
	cfg := logging.LogConfig{
		Fs:         afero.NewOsFs(),
		Level:      slog.LevelDebug,
		OutputType: logging.ColorOutput,
		LogToDisk:  true,
		LogPath:    filepath.Join("/tmp", "test.log"),
	}

	log, err := logging.InitLogging(&cfg)
	if err != nil {
		fmt.Println("Error initializing logger:", err)
		return
	}

	log.Println("This is a test info message")
	log.Printf("This is a test %s info message", "formatted")
	log.Error("This is a test error message")
	log.Debugf("This is a test debug message")
	log.Errorf("This is a test %s error message", "formatted")
	log.Println("{\"time\":\"2024-01-03T23:12:35.937476-07:00\",\"level\":\"ERROR\",\"msg\":\"\\u001b[1;32m==> docker.ansible-attack-box: Starting docker container...\\u001b[0m\"}")
}
Output:

func L added in v2.1.8

func L() Logger

L returns the global logger instance for use in logging operations.

**Returns:**

Logger: The global Logger instance.

type OutputType added in v2.1.8

type OutputType int

OutputType is an enumeration type that specifies the output format of the logger. It can be either plain text or colorized text.

const (
	// PlainOutput indicates that the logger will produce plain text
	// output without any colorization. This is suitable for log
	// files or environments where ANSI color codes are not supported.
	PlainOutput OutputType = iota

	// ColorOutput indicates that the logger will produce colorized
	// text output. This is useful for console output where color
	// coding can enhance readability.
	ColorOutput
)

type PlainLogger added in v2.0.6

type PlainLogger struct {
	Info   LogConfig
	Logger *slog.Logger
}

PlainLogger is a logger implementation using the slog library. It provides structured logging capabilities.

**Attributes:**

Info: LogConfig object containing information about the log file. Logger: The slog Logger instance used for logging operations.

func NewPlainLogger added in v2.2.1

func NewPlainLogger(cfg LogConfig, logger *slog.Logger) (*PlainLogger, error)

NewPlainLogger creates a new PlainLogger instance with the specified LogConfig and slog.Logger.

**Parameters:**

cfg: LogConfig object containing information about the log file. logger: The slog Logger instance used for logging operations.

**Returns:**

*PlainLogger: A new instance of PlainLogger. error: An error if any issue occurs during initialization.

func (*PlainLogger) Debug added in v2.1.1

func (l *PlainLogger) Debug(v ...interface{})

Debug for PlainLogger logs the provided arguments as a debug line using slog library. The arguments are converted to a string using fmt.Sprint.

func (*PlainLogger) Debugf added in v2.1.1

func (l *PlainLogger) Debugf(format string, v ...interface{})

Debugf for PlainLogger logs the provided formatted string as a debug line using slog library. The format and arguments are handled in the manner of fmt.Printf.

func (*PlainLogger) Error added in v2.0.7

func (l *PlainLogger) Error(v ...interface{})

Error for PlainLogger logs the provided arguments as an error line using slog library. The arguments are converted to a string using fmt.Sprint.

func (*PlainLogger) Errorf added in v2.0.7

func (l *PlainLogger) Errorf(format string, v ...interface{})

Errorf for PlainLogger logs the provided formatted string as an error line using slog library. The format and arguments are handled in the manner of fmt.Printf.

func (*PlainLogger) Printf added in v2.0.6

func (l *PlainLogger) Printf(format string, v ...interface{})

Printf for PlainLogger logs the provided formatted string using slog library. The format and arguments are handled in the manner of fmt.Printf.

func (*PlainLogger) Println added in v2.0.6

func (l *PlainLogger) Println(v ...interface{})

Println for PlainLogger logs the provided arguments as a line using slog library. The arguments are converted to a string using fmt.Sprint. PlainLogger.go

func (*PlainLogger) Warn added in v2.2.3

func (l *PlainLogger) Warn(v ...interface{})

Warn for PlainLogger logs the provided arguments as a warning line using slog library. The arguments are converted to a string using fmt.Sprint.

func (*PlainLogger) Warnf added in v2.2.3

func (l *PlainLogger) Warnf(format string, v ...interface{})

Warnf for PlainLogger logs the provided formatted string as a warning line using slog library. The format and arguments are handled in the manner of fmt.Printf.

type PrettyHandler added in v2.1.8

type PrettyHandler struct {
	slog.Handler
	// contains filtered or unexported fields
}

PrettyHandler is a custom log handler that provides colorized logging output. It wraps around slog.Handler and adds color to log messages based on their level.

**Attributes:**

Handler: The underlying slog.Handler used for logging. l: Standard logger used for outputting log messages.

func NewPrettyHandler added in v2.1.8

func NewPrettyHandler(out io.Writer, opts PrettyHandlerOptions) *PrettyHandler

NewPrettyHandler creates a new PrettyHandler with specified output writer and options. It configures the PrettyHandler for handling log messages with optional colorization and structured formatting.

**Parameters:**

out: Output writer where log messages will be written. opts: PrettyHandlerOptions for configuring the handler.

**Returns:**

*PrettyHandler: A new instance of PrettyHandler.

func (*PrettyHandler) Handle added in v2.1.8

func (h *PrettyHandler) Handle(ctx context.Context, r slog.Record) error

Handle processes and outputs a log record using the PrettyHandler. It supports both colorized and non-colorized log messages and can output in JSON format if not writing to a terminal.

**Parameters:**

ctx: Context for the log record. r: The log record containing log data.

**Returns:**

error: An error if any issue occurs during log handling.

type PrettyHandlerOptions added in v2.1.8

type PrettyHandlerOptions struct {
	SlogOpts slog.HandlerOptions
}

PrettyHandlerOptions represents options used for configuring the PrettyHandler.

**Attributes:**

SlogOpts: Options for the underlying slog.Handler.

Jump to

Keyboard shortcuts

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