it

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2024 License: MIT Imports: 14 Imported by: 1

README

it

Utility Functions for Error Handling, Logging, and Retry Logic in Go

GoDoc Go Report Card

Table of Contents

• Overview
• Features
• Installation
• Quick Start
• Usage Examples
• Error Handling
• Logging
• Structured Logging
• Retry and Exponential Backoff
• Graceful Actions
• Rate Limiters
• Utility Functions
• Configuration
• Documentation
• Contributing
• License

Overview

it is a Go package providing utility functions for error handling, logging, and execution retries, simplifying common patterns while adhering to Go best practices. It offers a collection of functions to manage errors, structured logging, retries with exponential backoff, and other robust utilities like graceful shutdown & restart of any server; with done notification as well as action functions to perform.

Features

• Simplified error handling with Must and Should
• Logging functions for different log levels: Trace, Debug, Info, Warn, Error, and Fatal
• Structured logging in JSON format for easy parsing and analysis
• Configurable log levels, outputs, and color-coded console output
• Utility functions for retry mechanisms, exponential backoff, and context-based retries
• Enhanced error wrapping, panic recovery, and timing functions

Installation

To install the it package, use go get:

go get github.com/theHamdiz/it

Import the package in your Go code:

import "github.com/theHamdiz/it"

Quick Start

package main

import (
    "fmt"
    "github.com/theHamdiz/it"
)

func main() {
    // Use Must for critical operations
    hardResult := it.Must(SomeCriticalFunction())

    // Use Should for operations where you can proceed on error
    softResult := it.Should(SomeNonCriticalFunction())

    fmt.Println("Hard Result:", hardResult)
    fmt.Println("Soft Result:", softResult)
}

func SomeCriticalFunction() (string, error) {
    return "", fmt.Errorf("critical error occurred")
}

func SomeNonCriticalFunction() (string, error) {
    return "default value", fmt.Errorf("non-critical error occurred")
}

Usage Examples

Error Handling
Must

Use Must when an error is unrecoverable and should halt the program execution.

result := it.Must(SomeFunction())
Should

Use Should when you want to log an error but continue execution.

 result := it.Should(SomeFunction())
Ensure

Panics if err is not nil. Use it when a critical error cannot be recovered.

it.Ensure(SomeCriticalFunction())
Attempt

Logs the error but continues execution. Use it for non-critical errors.

it.Attempt(SomeFunction())
WrapWithContext

Adds contextual information to an error message, making it easier to track errors.

err := it.WrapWithContext(err, "processing file", map[string]string{"file": filename})
Logging
Basic Logging
it.Info("Application started")  
it.Warn("Low disk space")  
it.Error("Failed to connect to database")
Formatted Logging
it.Infof("Server started on port %d", port)  
it.Warnf("Disk space low: %d%% remaining", diskSpace)  
it.Errorf("Error %d: %s", errorCode, errorMessage)

Debug and Trace Logging

Set the log level to include debug and trace messages:

it.SetLogLevel(it.LevelDebug)
Log messages
it.Debug("Cache initialized")
 
it.Trace("Entered function X")  

LogStackTrace

Logs the current stack trace, which is helpful for debugging complex issues by displaying the call stack.

func LogStackTrace()

Example Usage:

it.LogStackTrace()

LogErrorWithStack

Logs an error along with the current stack trace. This provides more detailed information to aid in debugging by capturing the error context and call stack.

func LogErrorWithStack(err error)
  • err: The error to log, along with its stack trace.

Example Usage:

it.LogErrorWithStack(err)
LogOnce

Logs a message only once, avoiding repetitive log entries in loops.

it.LogOnce("This message will only be logged once")
Audit

Logs an audit-specific message for tracking important actions.

 it.Audit("User login attempt recorded")
Structured Logging
Structured Info

Logs messages in JSON format with additional data.

userData := map[string]string{"username": "johndoe", "ip": "192.168.1.1"}
it.StructuredInfo("User logged in", userData)

StructuredDebug

Logs a structured debug-level message in JSON format, useful for detailed logging with additional contextual data.

func StructuredDebug(message string, data any)
  • message: The debug message to log.
  • data: Additional contextual data in key-value format.

Example Usage:

it.StructuredDebug("Cache hit", map[string]string{"key": "user:1234"})

StructuredWarning

Logs a structured warning message in JSON format with additional data. Useful for tracking non-critical issues in a structured way.

func StructuredWarning(message string, data any)
  • message: The warning message to log.
  • data: Additional key-value data to provide context.

Example Usage:

it.StructuredWarning("High memory usage detected", map[string]interface{}{"usage": 95})

StructuredError

Logs an error message in JSON format with additional contextual data, useful for error tracking with structured logs.

func StructuredError(message string, data any)  
  • message: The error message to log.
  • data: Additional context in a key-value format.

Example Usage:

it.StructuredError("File not found", map[string]string{"filename": "config.yaml"})  
BufferedLogger

Logs to any specified writer with buffering, supporting os.Stdout, file, or custom io.Writer.

file, _ := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
logger := it.NewBufferedLogger(file)
logger.Log("Buffered log message")
logger.Flush()

Retry and Exponential Backoff

Retry

Retries a function with a fixed delay. Useful for handling transient errors.

err := it.Retry(3, time.Second, SomeFunction)

RetryExponential

Retries a function with exponential backoff, doubling the delay after each attempt.

err := it.RetryExponential(5, time.Second, SomeFunction)

RetryWithContext

Retries a function with a fixed delay, stopping if the context is canceled.

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := it.RetryWithContext(ctx, 3, time.Second, SomeFunction)
RetryExponentialWithContext

Retries a function with exponential backoff, doubling the delay after each attempt, but stops if the context is canceled.

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)  
defer cancel()  
err := it.RetryExponentialWithContext(ctx, 5, time.Second, SomeFunction)  

Graceful Actions

GracefulShutdown

GracefulShutdown listens for an interrupt signal (e.g., SIGINT or SIGTERM) and attempts to gracefully shut down the given server within the specified timeout. If an action function is provided, it will execute this function after shutdown completes. If a done channel is provided, it will signal completion on the channel after the shutdown and executing the action.

func GracefulShutdown(ctx context.Context, server interface{ Shutdown(context.Context) error }, timeout time.Duration, done chan<- bool, action func())

ctx: The base context for shutdown, which can be context.Background() or another context.
server: The server object to shut down, which must have a Shutdown method that takes a context.Context.
timeout: The maximum time to wait for the server to shut down gracefully before forcing termination.
done: An optional channel to signal completion once the shutdown and action are complete. If done is nil, no notification is sent.
action: An optional function to execute after the server has shut down. This can be used for cleanup or other post-shutdown tasks. If action is nil, no action is performed.

Example Usage:

  1. Without a done channel or action:
it.GracefulShutdown(context.Background(), server, 5*time.Second, nil, nil)
  1. With a done channel and action:
done := make(chan bool)
cleanupAction := func() {
    log.Println("Performing post-shutdown cleanup...")
    // Additional cleanup code here
}
go it.GracefulShutdown(context.Background(), server, 5*time.Second, done, cleanupAction)
<-done // Wait for the shutdown process to complete

GracefulRestart

GracefulRestart listens for a signal to restart the server gracefully. It attempts to shut down the given server within the specified timeout and then optionally performs an action before signaling completion on the done channel, if provided.

func GracefulRestart(ctx context.Context, server interface{ Shutdown(context.Context) error }, timeout time.Duration, done chan<- bool, action func())

ctx: The context for shutdown, typically context.Background() or similar.
server: The server instance to restart, which must implement a Shutdown method.
timeout: The maximum time allowed for the graceful shutdown before initiating a restart.
done: An optional channel to signal completion once the shutdown, action, and restart are complete. If done is nil, no notification is sent.
action: An optional function to execute after the server has shut down. This can be used to reinitialize services, reload configurations, or perform any other custom restart logic. If action is nil, no action is performed.

Example Usage:

  1. Without a done channel or action:
it.GracefulRestart(context.Background(), server, 5*time.Second, nil, nil)
  1. With a done channel and an action:
done := make(chan bool)
restartAction := func() {
    log.Println("Performing custom restart actions...")
    // Additional initialization or setup code here
}
go it.GracefulRestart(context.Background(), server, 5*time.Second, done, restartAction)
<-done // Wait for the restart process to complete
RateLimiter

RateLimiter returns a rate-limited version of any handler function, allowing it to execute only once per specified rate interval. This function is designed to work with handlers of any type, including HTTP route handlers and custom functions with any signature.

func RateLimiter(rate time.Duration, fn interface{}) interface{}

• rate: The interval at which fn is allowed to execute. Only one call to fn will be allowed per rate period.
• fn: The original handler function to be rate-limited. It can have any number and type of input arguments and return any type.

Returns

A rate-limited function that has the same signature as fn. The returned function will wait for the specified rate interval before each execution.

Example Usage

With an HTTP Handler

func myHTTPHandler(w http.ResponseWriter, r *http.Request) {
 w.Write([]byte("Hello, World!"))
}

limitedHandler := it.RateLimiter(1*time.Second, myHTTPHandler).(func(http.ResponseWriter, *http.Request))
http.HandleFunc("/limited", limitedHandler)

In this example, myHTTPHandler is wrapped with RateLimiter, and it will execute at most once per second when called.

With a Custom Function

func customHandler(name string, age int) string {
 return fmt.Sprintf("Name: %s, Age: %d", name, age)
}

limitedCustomHandler := it.RateLimiter(2*time.Second, customHandler).(func(string, int) string)
result := limitedCustomHandler("Alice", 30)
fmt.Println(result) // Output: "Name: Alice, Age: 30"

Here, customHandler is rate-limited to execute at most once every two seconds, regardless of how often limitedCustomHandler is called.

Notes

• Generic Handler Support: RateLimiter is designed to work with any function signature, making it compatible with various handler types.
• Type Assertion: Since RateLimiter returns an interface{}, you will need to use type assertion to call the wrapped function with the correct parameter and return types.
• Rate Control: Calls to the returned function are delayed based on the specified rate, ensuring that fn is only invoked once per interval.

Utility Functions
WaitFor

Waits until a specified condition is met or times out.

it.WaitFor(time.Second*10, func() bool { return someCondition() })
DeferWithLog

Creates a deferred function that logs a message upon completion, helpful for complex defer chains.

defer it.DeferWithLog("Cleanup complete")()
TimeFunction

Measures and logs the execution time of a function.

it.TimeFunction("compute", compute)
TimeBlock

Starts a timer and logs the execution time of a code block.

defer it.TimeBlock("main")()
Configuration
Setting Log Output

Redirect logs to a file or other output destination.

file, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
it.SetLogOutput(file)
Setting Log Level

Control verbosity of logs:

it.SetLogLevel(it.LevelInfo)
Available levels

• it.LevelTrace
• it.LevelDebug
• it.LevelInfo
• it.LevelWarn
• it.LevelError
• it.LevelFatal
• it.LevelAudit

Environment Variables

Initialize logger settings from environment variables:

os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_FILE", "app.log")
it.InitFromEnv()
Supported variables

• LOG_LEVEL: TRACE, DEBUG, INFO, WARN, ERROR, FATAL
• LOG_FILE: Path to a file for log output

Documentation

For detailed documentation of all functions, visit the GoDoc page.

Contributing

Contributions are welcome! Please submit issues and pull requests for bug fixes, enhancements, or new features.

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/your-feature).
  3. Commit your changes (git commit -am 'Add new feature').
  4. Push to the branch (git push origin feature/your-feature).
  5. Open a pull request.

Please ensure your code adheres to Go conventions and includes tests where appropriate.

License

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

Thank you for using it! If you have any questions or feedback, feel free to open an issue or submit a pull request.

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

View Source
const (
	LevelTrace = iota
	LevelDebug
	LevelInfo
	LevelWarning
	LevelError
	LevelFatal
	LevelAudit
)

Define log levels

Variables

This section is empty.

Functions

func Attempt

func Attempt(err error)

Attempt logs the error with filename and line number if err is not nil, but allows the program to continue, much like Should but for methods that only return an error.

Example usage:

it.Attempt(SomeErrorOnlyFunction())

func Audit

func Audit(message string)

Audit logs a message with the custom Audit level. Use Audit for logging audit-related information.

Example usage:

it.Audit("User login attempt recorded")

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

func CheckErrorf(err error, format string, args ...interface{})

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 DeferWithLog

func DeferWithLog(message string) func()

DeferWithLog defers a function with an optional log message. Useful for managing complex defer chains with logs.

Example usage:

defer it.DeferWithLog("Cleanup complete")()

func Ensure

func Ensure(err error)

Ensure panics if err is not nil. Use Ensure for critical operations where an error is unacceptable, much like Must but for methods that only return error.

Example usage:

it.Ensure(SomeErrorOnlyFunction())

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 GracefulRestart

func GracefulRestart(ctx context.Context, server interface{ Shutdown(context.Context) error }, timeout time.Duration, done chan<- bool, action func())

GracefulRestart listens for a signal to restart the server gracefully. It can be used with any server that has a Shutdown method.

Example usage:

go it.GracefulRestart(context.Background(), server, 5*time.Second)

GracefulRestart listens for a signal to restart the server gracefully. It attempts to shut down the given server within the specified timeout and then optionally performs an action before signaling completion on the `done` channel, if provided.

Example usage:

it.GracefulRestart(context.Background(), server, 5*time.Second, nil, nil)

Or with a done channel and an action function:

done := make(chan bool)
restartAction := func() { log.Println("Performing custom restart actions...") }
go it.GracefulRestart(context.Background(), server, 5*time.Second, done, restartAction)
<-done

func GracefulShutdown

func GracefulShutdown(ctx context.Context, server interface{ Shutdown(context.Context) error }, timeout time.Duration, done chan<- bool, action func())

GracefulShutdown listens for an interrupt signal (e.g., SIGINT or SIGTERM) and attempts to gracefully shut down the given server within the specified timeout. If an `action` function is provided, it will be executed after shutdown completes. If a `done` channel is provided, it will signal completion on the channel after shutdown and executing the action.

Example usage:

it.GracefulShutdown(context.Background(), server, 5*time.Second, nil, nil)

Or with a done channel and an action function:

done := make(chan bool)
cleanupAction := func() { log.Println("Performing post-shutdown cleanup...") }
go it.GracefulShutdown(context.Background(), server, 5*time.Second, done, cleanupAction)
<-done

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 LogOnce

func LogOnce(message string)

LogOnce logs a message only once. Useful in scenarios where a repeated log would clutter output.

Example usage:

it.LogOnce("This message will only be logged once")

func LogStackTrace

func LogStackTrace()

LogStackTrace logs the current stack trace. Use LogStackTrace to debug complex issues.

Example usage:

it.LogStackTrace()

func Must

func Must[T any](x T, err error) T

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 RateLimiter

func RateLimiter(rate time.Duration, fn interface{}) interface{}

RateLimiter returns a rate-limited version of any handler function. The handler will only be allowed to execute once per specified `rate` interval. It supports handlers with any number of input arguments and return values.

Example usage:

limitedHandler := it.RateLimiter(1*time.Second, handler)
result := limitedHandler(arg1, arg2)

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 Retry

func Retry(attempts int, delay time.Duration, fn func() error) error

Retry retries the given function `fn` up to `attempts` times with a delay between attempts. Returns the error from the last attempt if all attempts fail.

Example usage:

err := it.Retry(3, time.Second, SomeErrorOnlyFunction)

func RetryExponential

func RetryExponential(attempts int, initialDelay time.Duration, fn func() error) error

RetryExponential retries the given function `fn` up to `attempts` times with an exponential backoff delay between attempts. The delay starts at `initialDelay` and doubles with each attempt. Returns the error from the last attempt if all attempts fail.

Example usage:

err := it.RetryExponential(5, time.Second, SomeErrorOnlyFunction)

func RetryExponentialWithContext

func RetryExponentialWithContext(ctx context.Context, attempts int, initialDelay time.Duration, fn func() error) error

RetryExponentialWithContext retries the given function `fn` up to `attempts` times with an exponential backoff delay between attempts. The delay starts at `initialDelay` and doubles with each attempt. If the context is canceled, it stops retrying and returns the context error.

Example usage:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := it.RetryExponentialWithContext(ctx, 5, time.Second, SomeErrorOnlyFunction)

func RetryWithContext

func RetryWithContext(ctx context.Context, attempts int, delay time.Duration, fn func() error) error

RetryWithContext retries a function while respecting context cancellation. It tries up to `attempts` times with a delay between each try and cancels if the context is done.

Example usage:

err := it.RetryWithContext(ctx, 3, time.Second, SomeErrorOnlyFunction)

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
    it.LevelAudit

Example usage:

it.SetLogLevel(it.LevelDebug)

func SetLogOutput

func SetLogOutput(output *os.File)

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

func Should[T any](x T, err error) T

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

func StructuredInfo(message string, data any)

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

func StructuredLog(level string, message string, data any)

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 WaitFor

func WaitFor(timeout time.Duration, condition func() bool) bool

WaitFor waits until the provided function returns true or times out after `timeout` duration. Useful for waiting on certain conditions in concurrent environments.

Example usage:

it.WaitFor(time.Second * 10, func() bool { return someCondition() })

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

func WrapError(err error, message string) error

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 WrapErrorWithContext added in v1.1.0

func WrapErrorWithContext(err error, message string, context map[string]string) error

WrapErrorWithContext wraps an error with additional contextual information. Useful for adding more details to errors without losing the original error.

Example usage:

err := it.WrapErrorWithContext(err, "processing file", map[string]string{"file": filename})

func WrapErrorf added in v1.0.1

func WrapErrorf(err error, format string, args ...interface{}) error

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 BufferedLogger

type BufferedLogger struct {
	// contains filtered or unexported fields
}

BufferedLogger provides a buffered logging mechanism, allowing logs to be written to any io.Writer.

func NewBufferedLogger

func NewBufferedLogger(output io.Writer) *BufferedLogger

NewBufferedLogger creates a new BufferedLogger that writes to the specified io.Writer.

Example usage:

file, _ := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
defer file.Close()
logger := it.NewBufferedLogger(file)
logger.Log("Logging to a file")

func (*BufferedLogger) Flush

func (b *BufferedLogger) Flush() error

Flush forces any buffered data to be written out to the underlying writer. Useful for ensuring all logs are written at program exit.

Example usage:

logger.Flush()

func (*BufferedLogger) Log

func (b *BufferedLogger) Log(message string)

Log writes a message to the buffered writer and flushes the buffer.

Example usage:

logger := it.NewBufferedLogger(os.Stdout)
logger.Log("Logging to standard output")

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger struct to manage log level

func NewLogger

func NewLogger(options ...LoggerOption) *Logger

NewLogger creates a logger with configurable options.

Example usage:

logger := it.NewLogger(it.WithLogLevel(it.LevelDebug), it.WithTimestamp(true))

type LoggerOption

type LoggerOption func(*LoggerOptions)

LoggerOption is a functional option type for configuring Logger.

func WithLogLevel

func WithLogLevel(level int) LoggerOption

WithLogLevel sets the log level for Logger.

func WithTimestamp

func WithTimestamp(enabled bool) LoggerOption

WithTimestamp enables timestamp logging.

type LoggerOptions

type LoggerOptions struct {
	// contains filtered or unexported fields
}

type StructuredLogEntry

type StructuredLogEntry struct {
	Level   string `json:"level"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

StructuredLogEntry represents a structured log message.

Jump to

Keyboard shortcuts

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