fastlog

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2024 License: MIT Imports: 9 Imported by: 0

README

fastlog

fastlog is a high-performance logging package for Go, designed to be extremely fast, efficient, and suitable for high-performance applications. It supports logging to both files and standard output, with features such as buffering, non-blocking I/O, periodic flushing, log rotation, and configurable log levels.

Features

  • Log Levels: Supports DEBUG, INFO, WARN, ERROR, and FATAL levels.
  • Buffering: Uses a buffer to minimize I/O operations.
  • Non-blocking I/O: Log messages are sent to a channel and processed by a separate goroutine.
  • Periodic Flushing: Flushes logs every 5 seconds.
  • Log Rotation: Automatically rotates log files when they exceed a predefined size.
  • Configurable Output: Logs can be written to a file or standard output based on configuration.
  • Structured Logging: Supports structured logging and JSON formatted logs.

Installation

To install fastlog, run:

go get github.com/amarsinghrathour/fastlog

Usage

Here's an example of how to use fastlog:

    package main

    import (
        "log"
        "os"
        "path/filepath"
        "time"
    
        "github.com/yourusername/fastlog"
    )

    func main() {
        logDir := "logs"
        baseLogFileName := filepath.Join(logDir, "app.log")
    
        err := os.MkdirAll(logDir, 0755)
        if err != nil {
            log.Fatalf("Failed to create log directory: %v", err)
        }
    
        // Configure to log to a file
        loggerConfig := fastlog.LoggerConfig{
            Level:       fastlog.DEBUG,
            FilePath:    baseLogFileName,
            RotationDir: logDir,
            Stdout:      false, // Set to true to log to stdout instead of a file
            JSONFormat:  true,  // Set to true to enable JSON formatted logs
        }
    
        logger, err := fastlog.NewLogger(loggerConfig)
        if err != nil {
            log.Fatalf("Failed to create logger: %v", err)
        }
        defer logger.Close()
    
        // Log various messages
        logger.Debug("This is a debug message", "key1", "value1")
        logger.Info("This is an info message", "key2", "value2")
        logger.Warn("This is a warning message", "key3", "value3")
        logger.Error("This is an error message", "key4", "value4")
    
        // Simulate some work to generate logs over time
        for i := 0; i < 10; i++ {
            logger.Info("Working on task", "iteration", i)
            time.Sleep(1 * time.Second)
        }
    
        // Log a fatal message (this will terminate the program)
        logger.Fatal("This is a fatal message", "key5", "value5")
    }



MIT License Go Reference

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LogLevel

type LogLevel int

LogLevel defines the severity of the log message.

const (
	DEBUG LogLevel = iota // Debug level for detailed internal information.
	INFO                  // Info level for general operational messages.
	WARN                  // Warn level for warnings about potential issues.
	ERROR                 // Error level for error messages indicating problems.
	FATAL                 // Fatal level for critical issues that require program exit.
)

Enumeration of different log levels.

type Logger

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

Logger represents a logger with buffering and log rotation capabilities.

func NewLogger

func NewLogger(config LoggerConfig) (*Logger, error)

NewLogger creates a new Logger instance based on the provided LoggerConfig.

Parameters:

config: LoggerConfig containing the configuration options for the Logger.

Returns:

(*Logger, error): A pointer to the Logger instance and any error encountered during initialization.

Example usage:

config := LoggerConfig{
  Level:      INFO,
  FilePath:   "logs/myapp.log",
  RotationDir: "logs/rotation",
  Stdout:     false,
  JSONFormat: true,
}
logger, err := NewLogger(config)
if err != nil {
  log.Fatalf("Failed to create logger: %v", err)
}
defer logger.Close()

Notes: - If Stdout is true, log messages are directed to standard output (os.Stdout). - If Stdout is false, a log file is created or opened based on FilePath for writing log messages. - The log directory specified in FilePath or RotationDir is created if it doesn't exist. - The logger starts background goroutines for processing log messages from the queue and periodic buffer flushing.

func (*Logger) Close

func (l *Logger) Close()

Close flushes the buffer and closes the log file. It ensures that all pending log messages are flushed to the underlying log file or stdout, and then closes the log file if it was opened during logger initialization. The method also ensures that the logger's resources are cleaned up properly by closing the done channel once to signal the termination of background goroutines.

If an error occurs during flushing the buffer or closing the log file, it prints an error message to stderr with details about the specific error encountered.

Example usage:

logger.Close()

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

Debug logs a message at the DEBUG level. It logs the provided arguments at the DEBUG level using the log method. Debug-level messages are used for detailed internal information, typically useful for debugging purposes.

Args:

args: Variadic list of arguments to log as the message.

Example usage:

logger.Debug("Received request", requestID)

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

Error logs a message at the ERROR level. It logs the provided arguments at the ERROR level using the log method. If the log level threshold is set to ERROR or lower, the message will be written to the log output (stdout or file), ensuring it is captured for error reporting.

Args:

args: Variadic list of arguments to log as the message.

Example usage:

logger.Error("Failed to process request:", err)

func (*Logger) Fatal

func (l *Logger) Fatal(args ...interface{})

Fatal logs a message at the FATAL level, writes it to the log output, and exits the application. It logs the provided arguments at the FATAL level using the log method, ensuring the message is written even if it exceeds the log level threshold. After logging, it closes the log file using Close method to flush any remaining log messages in the buffer and close the file handle. Finally, it terminates the application by calling os.Exit(1), indicating a critical error.

This method is intended for logging critical errors that necessitate immediate application termination.

Args:

args: Variadic list of arguments to log as the message.

Example usage:

logger.Fatal("Critical error occurred: database connection lost")

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

Info logs a message at the INFO level. It logs the provided arguments at the INFO level using the log method. If the log level threshold is set to INFO or lower, the message will be written to the log output (stdout or file), providing general operational messages or information.

Args:

args: Variadic list of arguments to log as the message.

Example usage:

logger.Info("Application started successfully.")

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

Warn logs a message at the WARN level. It logs the provided arguments at the WARN level using the log method. If the log level threshold is set to WARN or lower, the message will be written to the log output (stdout or file), indicating potential issues or warnings.

Args:

args: Variadic list of arguments to log as the message.

Example usage:

logger.Warn("Connection timeout. Retrying...")

type LoggerConfig

type LoggerConfig struct {
	Level       LogLevel // Log level threshold.
	FilePath    string   // Path to the log file.
	RotationDir string   // Directory for rotated log files.
	Stdout      bool     // Whether to log to stdout instead of a file.
	JSONFormat  bool     // Whether to log in JSON format.
}

LoggerConfig defines the configuration for the Logger.

Jump to

Keyboard shortcuts

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