it

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2024 License: MIT Imports: 8 Imported by: 1

README

��# it

Utility Functions for Error Handling and Logging in Go

GoDoc Go Report Card

Table of Contents

Overview

it is a Go package that provides utility functions for error handling and logging, simplifying common patterns while adhering to Go's best practices. It offers a collection of functions to manage errors by panicking on unrecoverable errors, logging errors while continuing execution, and other utilities for robust error handling.

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 and outputs
  • Color-coded console output for enhanced readability
  • Utilities for 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) {
    // Simulate a critical function that may fail
    return "", fmt.Errorf("critical error occurred")
}

func SomeNonCriticalFunction() (string, error) {
    // Simulate a non-critical function that may fail
    return "default value", fmt.Errorf("non-critical error occurred")
}

Usage Examples

Error Handling Functions

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())

Logging Functions

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) // or it.LevelTrace

Log messages:

it.Debug("Cache initialized")
it.Trace("Entered function X")

Structured Logging

Structured Info

Log messages in JSON format with additional data:

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

Output:

{"level":"INFO","message":"User logged in","data":{"username":"johndoe","ip":"192.168.1.1"}}

Advanced Usage

Setting Log Output

Redirect logs to a file:

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)
Error Wrapping

Add context to errors:

func readFile(filename string) error {
    _, err := os.Open(filename)
    if err != nil {
        return it.WrapErrorf(err, "failed to open file %s", filename)
    }
    return nil
}
Panic Recovery

Gracefully handle panics:

func main() {
    defer it.RecoverPanic()
    // Code that may panic
    panic("unexpected error")
}
Timing Functions

Measure function execution time:

it.TimeFunction("compute", compute)

Measure code block execution time:

defer it.TimeBlock("main")()
// Code block to measure

Configuration

Setting Log Level

Control the verbosity of logs:

it.SetLogLevel(it.LevelInfo) // Default level
it.SetLogLevel(it.LevelDebug)

Available levels:

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

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.

To contribute:

  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
)

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

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 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

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 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

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

Jump to

Keyboard shortcuts

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