Documentation
¶
Overview ¶
Package it provides utility functions for error handling and logging, simplifying common patterns while adhering to Go's best practices.
This package includes functions that help manage errors by panicking on unrecoverable errors, logging errors while continuing execution, and other utilities for robust error handling.
Example usage:
import "github.com/theHamdiz/it"
func main() {
hardResult := it.Must(SomeFunction())
softResult := it.Should(SomeFunction())
fmt.Println(hardResult)
fmt.Println(softResult)
}
Index ¶
- Constants
- func CheckError(err error)
- func CheckErrorf(err error, format string, args ...interface{})
- func Debug(message string)
- func Debugf(format string, args ...interface{})
- func Error(message string)
- func Errorf(format string, args ...interface{})
- func Info(message string)
- func Infof(format string, args ...interface{})
- func InitFromEnv()
- func LogError(err error)
- func LogErrorWithStack(err error)
- func LogStackTrace()
- func Must[T any](x T, err error) T
- func RecoverPanicAndContinue()
- func RecoverPanicAndExit()
- func SetLogLevel(level int)
- func SetLogOutput(output *os.File)
- func Should[T any](x T, err error) T
- func StructuredDebug(message string, data interface{})
- func StructuredError(message string, data interface{})
- func StructuredInfo(message string, data any)
- func StructuredLog(level string, message string, data any)
- func StructuredWarning(message string, data interface{})
- func TimeBlock(name string) func()
- func TimeFunction(name string, f func())
- func Trace(message string)
- func Tracef(format string, args ...interface{})
- func Warn(message string)
- func Warnf(format string, args ...interface{})
- func WrapError(err error, message string) error
- func WrapErrorf(err error, format string, args ...interface{}) error
- type Logger
- type StructuredLogEntry
Constants ¶
const ( LevelTrace = iota LevelDebug LevelInfo LevelWarning LevelError LevelFatal )
Define log levels
Variables ¶
This section is empty.
Functions ¶
func CheckError ¶
func CheckError(err error)
CheckError logs the error and exits the program if err is not nil. Use CheckError when an error is unrecoverable and the program should terminate.
Example usage:
it.CheckError(err)
func CheckErrorf ¶
CheckErrorf logs a formatted error message and exits the program if err is not nil. Use CheckErrorf when an error is unrecoverable and the program should terminate.
Example usage:
it.CheckErrorf(err, "Failed to start server on port %d", port)
func Debug ¶
func Debug(message string)
Debug logs a debug-level message. Use Debug to log detailed information useful for debugging.
Example usage:
it.Debug("Loaded configuration successfully")
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs a formatted debug-level message. Use Debugf to log detailed formatted information useful for debugging.
Example usage:
it.Debugf("User %s has %d pending messages", username, messageCount)
func Error ¶
func Error(message string)
Error logs an error message. Use Error to log errors that occurred during execution.
Example usage:
it.Error("Failed to connect to the database")
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs a formatted error message. Use Errorf to log formatted errors that occurred during execution.
Example usage:
it.Errorf("Failed to connect to the database: %v", err)
func Info ¶
func Info(message string)
Info logs an informational message. Use Info to log general information about the program's execution.
Example usage:
it.Info("Starting the application")
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs a formatted informational message. Use Infof to log formatted information about the program's execution.
Example usage:
it.Infof("Starting the application version %s", version)
func InitFromEnv ¶
func InitFromEnv()
InitFromEnv initializes the logger settings from environment variables. Supported environment variables: - LOG_LEVEL: TRACE, DEBUG, INFO, WARN, ERROR, FATAL - LOG_FILE: Path to a file to write logs to
Example usage:
it.InitFromEnv()
func LogError ¶
func LogError(err error)
LogError logs the error with the filename and line number if err is not nil. Use LogError when you want to log an error but handle it manually.
Example usage:
if err != nil {
it.LogError(err)
// Additional error handling...
}
func LogErrorWithStack ¶
func LogErrorWithStack(err error)
LogErrorWithStack logs an error along with the current stack trace. Use LogErrorWithStack to provide detailed error information.
Example usage:
if err != nil {
it.LogErrorWithStack(err)
}
func LogStackTrace ¶
func LogStackTrace()
LogStackTrace logs the current stack trace. Use LogStackTrace to debug complex issues.
Example usage:
it.LogStackTrace()
func Must ¶
Must returns the value x if err is nil. If err is not nil, Must panics with the error. Use Must when an error is unrecoverable and should halt the program execution.
Example usage:
result := it.Must(SomeFunction())
func RecoverPanicAndContinue ¶
func RecoverPanicAndContinue()
RecoverPanicAndContinue returns a function suitable for use with defer. It recovers from a panic, logs the error and stack trace.
func RecoverPanicAndExit ¶
func RecoverPanicAndExit()
RecoverPanicAndExit recovers from a panic, logs the error and stack trace, and exits. Use RecoverPanic with defer to handle panics gracefully.
Example usage:
defer it.RecoverPanic()
func SetLogLevel ¶
func SetLogLevel(level int)
SetLogLevel sets the minimum log level for logging. Messages below this level will not be logged.
Available log levels:
it.LevelTrace it.LevelDebug it.LevelInfo it.LevelWarn it.LevelError it.LevelFatal
Example usage:
it.SetLogLevel(it.LevelDebug)
func SetLogOutput ¶
SetLogOutput sets the output destination for logs. It can be a file, os.Stdout, os.Stderr, or any io.Writer.
Example usage:
file, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
it.Fatalf("Failed to open log file: %v", err)
}
defer file.Close()
it.SetLogOutput(file)
func Should ¶
Should returns the value x regardless of whether err is nil. If err is not nil, Should logs the error with the filename and line number. Use Should when you want to log an error but continue execution.
Note: Be cautious when using Should, as x may be in an invalid state if err is not nil. Ensure that the returned value is safe to use in such cases.
Example usage:
result := it.Should(SomeFunction())
func StructuredDebug ¶
func StructuredDebug(message string, data interface{})
func StructuredError ¶
func StructuredError(message string, data interface{})
StructuredError logs an error message in a structured format. Use StructuredError to log errors with additional data for better analysis.
Example usage:
it.StructuredError("File not found", map[string]string{"filename": "config.yaml"})
func StructuredInfo ¶
StructuredInfo logs an informational message in a structured (e.g., JSON) format. Use StructuredInfo to log messages with additional data in a structured format for easier parsing and analysis.
Example usage:
it.StructuredInfo("User logged in", map[string]string{"username": "johndoe", "ip": "192.168.1.1"})
func StructuredLog ¶
StructuredLog logs a message with a specified level in a structured format. Use StructuredLog to log messages with additional data for any log level.
Example usage:
it.StructuredLog("ERROR", "Failed to process request", map[string]interface{}{"requestID": "abc123", "error": err})
func StructuredWarning ¶
func StructuredWarning(message string, data interface{})
func TimeBlock ¶
func TimeBlock(name string) func()
TimeBlock starts a timer and returns a function to stop the timer and log the duration. Use TimeBlock with defer to measure the execution time of a code block.
Example usage:
defer it.TimeBlock("main")()
func TimeFunction ¶
func TimeFunction(name string, f func())
TimeFunction measures and logs the execution time of a function. Use TimeFunction to profile the performance of specific functions.
Example usage:
it.TimeFunction("compute", compute)
func Trace ¶
func Trace(message string)
Trace logs a trace-level message. Use Trace to log very detailed information for tracing program execution.
Example usage:
it.Trace("Entering function X")
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef logs a formatted trace-level message. Use Tracef to log formatted detailed tracing information.
Example usage:
it.Tracef("Processing item %d of %d", currentItem, totalItems)
func Warn ¶
func Warn(message string)
Warn logs a warning message. Use Warn to log non-critical issues that should be addressed.
Example usage:
it.Warn("Configuration file not found, using defaults")
func Warnf ¶
func Warnf(format string, args ...interface{})
Warnf logs a formatted warning message. Use Warnf to log formatted non-critical issues.
Example usage:
it.Warnf("Configuration file %s not found, using defaults", configFile)
func WrapError ¶
WrapError wraps an error with a message. Use WrapError to add context to an error.
Example usage:
return it.WrapError(err, "failed to open file")
func WrapErrorf ¶ added in v1.0.1
WrapErrorf wraps an error with a formatted message. Use WrapErrorf to add formatted context to an error.
Example usage:
return it.WrapErrorf(err, "failed to open file %s", filename)
Types ¶
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger struct to manage log level
type StructuredLogEntry ¶
type StructuredLogEntry struct {
Level string `json:"level"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
StructuredLogEntry represents a structured log message.