Documentation
¶
Index ¶
- func DetermineLogLevel(levelStr string) slog.Level
- func LogAndReturnError(logger Logger, errMsg string) error
- type ColorLogger
- func (l *ColorLogger) Debug(v ...interface{})
- func (l *ColorLogger) Debugf(format string, v ...interface{})
- func (l *ColorLogger) Error(v ...interface{})
- func (l *ColorLogger) Errorf(format string, v ...interface{})
- func (l *ColorLogger) Printf(format string, v ...interface{})
- func (l *ColorLogger) Println(v ...interface{})
- func (l *ColorLogger) Warn(v ...interface{})
- func (l *ColorLogger) Warnf(format string, v ...interface{})
- type LogConfig
- type Logger
- type OutputType
- type PlainLogger
- func (l *PlainLogger) Debug(v ...interface{})
- func (l *PlainLogger) Debugf(format string, v ...interface{})
- func (l *PlainLogger) Error(v ...interface{})
- func (l *PlainLogger) Errorf(format string, v ...interface{})
- func (l *PlainLogger) Printf(format string, v ...interface{})
- func (l *PlainLogger) Println(v ...interface{})
- func (l *PlainLogger) Warn(v ...interface{})
- func (l *PlainLogger) Warnf(format string, v ...interface{})
- type PrettyHandler
- type PrettyHandlerOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DetermineLogLevel ¶ added in v2.2.3
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
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
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
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
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
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:
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 // JSONOutput indicates that the logger will produce JSON formatted // output. This is useful for structured logging and log aggregation. JSONOutput )
type PlainLogger ¶ added in v2.0.6
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 Level slog.Level OutputType OutputType // 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. Level: The log level for the handler. OutputType: The type of output for the handler.
func NewPrettyHandler ¶ added in v2.1.8
func NewPrettyHandler(out io.Writer, opts PrettyHandlerOptions, outputType OutputType) *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. outputType: Type of output for the handler.
**Returns:**
*PrettyHandler: A new instance of PrettyHandler.
func (*PrettyHandler) Handle ¶ added in v2.1.8
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.