asynclog

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2024 License: MIT Imports: 9 Imported by: 0

README

AsyncLog: An Asynchronous Logging Package for Go

AsyncLog is a versatile and efficient asynchronous logging library for Go, designed for multi-level logging with support for custom formatting, colored output, and file logging capabilities.

Features

  • Asynchronous Logging: Processes log messages in a separate goroutine for minimal impact on main application flow.
  • Multiple Log Levels: Supports levels like Trace, Debug, Info, Warning, Error, and Fatal for detailed logging.
  • Customizable Output: Route log messages to different files or the console.
  • Colored console output: Enhances readability with color-coded logs in the console.
  • Source Code Information: Option to include source file and line number in logs.
  • Flexible Configuration: Tailor logger behavior with functional options.
  • Parameter Formatting: Choose between JSON or Key-Value formatting for log parameters.
  • File Logging: Direct logs to files with configurable file names and output settings.

Installation

Install AsyncLog using go get:

go get github.com/simp-lee/asynclog

Quick Start

Here's a basic example to get started with asynclog:

package main

import (
    "github.com/simp-lee/asynclog"
    "time"
)

func main() {
    // Create a new logger
    logger, err := asynclog.NewLogger()
    if err != nil {
        panic(err)
    }
    defer logger.Close() // Ensure logger is closed at the end
	
    // Logging at different levels
    logger.Trace("This is a trace message")
    logger.Debug("Debugging information here")
    logger.Info("Informational message")
    logger.Warning("This is a warning")
    logger.Error("Encountered an error")
    // Use Fatal sparingly - high severity
    logger.Fatal("Fatal error occurred")
	
    // Wait for a moment to ensure all messages are processed
    time.Sleep(1 * time.Second)
}

Configuration

Customize the logger at instantiation with various options:

logger, err := asynclog.NewLogger(
    asynclog.SetBufferSize(200),                             // Custom buffer size
    asynclog.SetFileLevel(asynclog.LogLevelInfo),            // Set file logging level
    asynclog.SetConsoleLevel(asynclog.LogLevelDebug),        // Set console logging level
    asynclog.EnableSourceInfo(true),                         // Enable source file information recording
    asynclog.SetDefaultFileName("app.log"),                  // Set default log file name
    asynclog.EnableFileOutput(false),                        // Disable file output
    asynclog.EnableConsoleOutput(true),                      // Enable console output
    asynclog.SetParamFormatter(asynclog.FormatParamsAsJSON), // Log parameter formatting
    asynclog.SetMaxFileHandles(20),                          // Set maximum number of file handles
)

Parameters and Formatting

Include additional parameters in your log messages and customize their formatting style:

params := map[string]interface{}{
    "user_id": 123,
    "action": "login",
}
logger.Info("User action", asynclog.SetLogParams(params)) // Log with additional parameters

Contributing

Your contributions to AsyncLog are welcome! Feel free to open issues or submit pull requests for improvements or new features.

Documentation

Index

Constants

View Source
const (
	LogLevelTrace LogLevel = iota
	LogLevelDebug
	LogLevelInfo
	LogLevelWarning
	LogLevelError
	LogLevelFatal

	// DefaultBufferSize is the default size of the log message channel.
	DefaultBufferSize = 100

	// DefaultFileName is the default name for log files.
	DefaultFileName = "default.log"

	// DefaultMaxFileHandles is the default maximum number of file handles.
	DefaultMaxFileHandles = 10

	// DefaultUnusedFileHandleThreshold is the threshold for cleaning up unused file handles.
	DefaultUnusedFileHandleThreshold = 30 * time.Minute

	// DefaultCleanupTicker is the interval for the cleanup routine.
	DefaultCleanupTicker = 10 * time.Minute
)

Variables

This section is empty.

Functions

func FormatParamsAsJSON

func FormatParamsAsJSON(params map[string]interface{}) string

FormatParamsAsJSON formats parameters as a JSON string.

func FormatParamsAsKeyValue

func FormatParamsAsKeyValue(params map[string]interface{}) string

FormatParamsAsKeyValue formats parameters as key-value pairs.

Types

type LogLevel

type LogLevel int

LogLevel defines the severity of a log message.

func (LogLevel) String

func (level LogLevel) String() string

String returns a string representation of the log level.

type LogMessage

type LogMessage struct {
	Level          LogLevel               // Log level of the message (e.g., DEBUG, INFO, etc.)
	Message        string                 // The actual log message
	FileMessage    string                 // Formatted message for file output
	ConsoleMessage string                 // Formatted message for console output
	File           string                 // The target log file
	Params         map[string]interface{} // Additional parameters for the log message
}

LogMessage represents a log message with its level, content, and additional parameters.

type LogOption

type LogOption func(*LogMessage)

LogOption defines a function type for log message configuration.

func SetLogFile

func SetLogFile(file string) LogOption

SetLogFile specifies the log file for a log message. This function is used to set a custom log file for individual log messages.

func SetLogParams

func SetLogParams(params map[string]interface{}) LogOption

SetLogParams specifies additional parameters for a log message. This function allows adding key-value pairs that provide additional information for the log message.

type Logger

type Logger struct {
	LogChannel      chan LogMessage // Channel for log messages.
	FileLevel       LogLevel        // Minimum level of messages to log to file.
	ConsoleLevel    LogLevel        // Minimum level of messages to log to console.
	DefaultFileName string          // Default log file name.
	OutputToFile    bool            // Flag to enable or disable file output.
	OutputToConsole bool            // Flag to enable or disable console output.

	AddSource bool // Flag to add source file info in logs.
	// contains filtered or unexported fields
}

Logger represents an asynchronous logger.

func NewLogger

func NewLogger(opts ...LoggerOption) (*Logger, error)

NewLogger creates a new Logger with specified options. opts are functional options to configure the Logger.

func (*Logger) Close

func (l *Logger) Close()

func (*Logger) Debug

func (l *Logger) Debug(message string, opts ...LogOption)

Debug logs a message at the Debug level.

func (*Logger) Error

func (l *Logger) Error(message string, opts ...LogOption)

Error logs a message at the Error level.

func (*Logger) Fatal

func (l *Logger) Fatal(message string, opts ...LogOption)

Fatal logs a message at the Fatal level.

func (*Logger) Info

func (l *Logger) Info(message string, opts ...LogOption)

Info logs a message at the Info level.

func (*Logger) Trace

func (l *Logger) Trace(message string, opts ...LogOption)

Trace logs a message at the Trace level.

func (*Logger) Warning

func (l *Logger) Warning(message string, opts ...LogOption)

Warning logs a message at the Warning level.

type LoggerOption

type LoggerOption func(*Logger) error

LoggerOption defines a function type for logger configuration options.

func EnableConsoleOutput

func EnableConsoleOutput(enable bool) LoggerOption

EnableConsoleOutput enables or disables console output.

func EnableFileOutput

func EnableFileOutput(enable bool) LoggerOption

EnableFileOutput enables or disables file output.

func EnableSourceInfo

func EnableSourceInfo(enable bool) LoggerOption

EnableSourceInfo enables or disables the logging of source file information.

func SetBufferSize added in v1.0.2

func SetBufferSize(size int) LoggerOption

SetBufferSize sets the size of the log message channel.

func SetConsoleLevel

func SetConsoleLevel(level LogLevel) LoggerOption

SetConsoleLevel sets the console log level.

func SetDefaultFileName

func SetDefaultFileName(fileName string) LoggerOption

SetDefaultFileName sets the default log file name.

func SetFileLevel

func SetFileLevel(level LogLevel) LoggerOption

SetFileLevel sets the file log level.

func SetMaxFileHandles

func SetMaxFileHandles(maxHandles int) LoggerOption

SetMaxFileHandles sets the maximum number of file handles.

func SetParamFormatter

func SetParamFormatter(formatter ParamFormatter) LoggerOption

SetParamFormatter sets the parameter formatting strategy for the logger.

type ParamFormatter

type ParamFormatter func(map[string]interface{}) string

ParamFormatter is a function type for formatting log parameters.

Jump to

Keyboard shortcuts

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