Skip to content

The logger package (github.com/hoanle396/logger) is a Go logging utility that provides structured logging capabilities with customizable prefixes and multiple log levels.

Notifications You must be signed in to change notification settings

Hoanle396/logger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Go Colored Logger Package

A comprehensive, easy-to-use logging package for Go applications with colored output, multiple log levels, and flexible configuration options.

Features

  • 🌈 Colored Output: Beautiful colored console output for different log levels
  • πŸ“Š Multiple Log Levels: VERBOSE, DEBUG, INFO, SUCCESS, WARNING, ERROR, FATAL
  • βš™οΈ Configurable: Customizable prefixes, timestamps, colors, and log levels
  • πŸš€ Easy to Use: Simple API with both global and instance-based usage
  • πŸ“¦ Zero Dependencies: No external dependencies required
  • 🎯 Production Ready: Includes production-friendly logger configurations

Installation

To install this package, use go get:

go get github.com/hoanle396/logger

Then import it in your Go files:

import "github.com/hoanle396/logger"

Quick Start

Basic Usage

package main

import "github.com/hoanle396/logger"

func main() {
    logger.Info("Application started")
    logger.Success("Operation completed successfully")
    logger.Warning("This is a warning")
    logger.Error("An error occurred")
    logger.Debug("Debug information")
    logger.Verbose("Verbose details")
}

Custom Logger Instance

package main

import "github.com/hoanle396/logger"

func main() {
    // Create a custom logger
    myLogger := logger.NewLogger()
    myLogger.SetPrefix("MYAPP")
    myLogger.SetLevel(logger.DEBUG)
    
    myLogger.Info("Custom logger message")
    myLogger.Debug("Debug with custom logger")
}

Log Levels

The package supports the following log levels (in order of priority):

Level Description Color Use Case
VERBOSE Detailed tracing information Gray Development debugging
DEBUG Debug information Cyan Development
INFO General information Blue General app flow
SUCCESS Success operations Green Successful operations
WARNING Warning conditions Yellow Potential issues
ERROR Error conditions Red Errors that don't stop execution
FATAL Fatal errors Red Critical errors (exits program)

API Reference

Global Functions

These functions use the default global logger instance:

logger.Verbose(message string, args ...interface{})
logger.Debug(message string, args ...interface{})
logger.Info(message string, args ...interface{})
logger.Success(message string, args ...interface{})
logger.Warning(message string, args ...interface{})
logger.Error(message string, args ...interface{})
logger.Fatal(message string, args ...interface{})

Global Configuration

Configure the default logger:

logger.SetLevel(logger.DEBUG)        // Set minimum log level
logger.SetShowTime(false)            // Disable timestamps
logger.SetColorized(false)           // Disable colors
logger.SetPrefix("MYAPP")            // Set prefix for all messages

Logger Instance Methods

Creating Loggers

// Standard logger with default settings
logger := logger.NewLogger()

Instance Configuration

logger.SetLevel(level LogLevel)      // Set minimum log level
logger.SetShowTime(show bool)        // Enable/disable timestamps
logger.SetColorized(colorized bool)  // Enable/disable colors
logger.SetPrefix(prefix string)      // Set message prefix

Instance Logging Methods

logger.Verbose(message string, args ...interface{})
logger.Debug(message string, args ...interface{})
logger.Info(message string, args ...interface{})
logger.Success(message string, args ...interface{})
logger.Warning(message string, args ...interface{})
logger.Error(message string, args ...interface{})
logger.Fatal(message string, args ...interface{})

Examples

1. Basic Logging

logger.Info("Server starting on port %d", 8080)
logger.Success("Database connection established")
logger.Warning("Memory usage is at %d%%", 85)
logger.Error("Failed to process request: %v", err)

2. Log Level Filtering

// Set to WARNING level - only WARNING, ERROR, and FATAL will show
logger.SetLevel(logger.WARNING)

logger.Debug("This won't show")     // Hidden
logger.Info("This won't show")      // Hidden
logger.Warning("This will show")    // Visible
logger.Error("This will show")      // Visible

3. Custom Logger for Different Components

// Database logger
dbLogger := logger.NewLogger()
dbLogger.SetPrefix("DB")
dbLogger.Info("Connection pool initialized")

// HTTP logger
httpLogger := logger.NewLogger()
httpLogger.SetPrefix("HTTP")
httpLogger.Info("Server listening on :8080")

// Auth logger
authLogger := logger.NewLogger()
authLogger.SetPrefix("AUTH")
authLogger.Warning("Failed login attempt from %s", clientIP)

5. Disabling Colors for CI/CD

// Disable colors when running in CI/CD environments
if os.Getenv("CI") != "" {
    logger.SetColorized(false)
}

6. Application Workflow

func main() {
    appLogger := logger.NewLogger()
    appLogger.SetPrefix("MYAPP")
    
    appLogger.Info("Application starting...")
    
    appLogger.Debug("Loading configuration...")
    if err := loadConfig(); err != nil {
        appLogger.Fatal("Failed to load configuration: %v", err)
    }
    appLogger.Success("Configuration loaded")
    
    appLogger.Debug("Connecting to database...")
    if err := connectDB(); err != nil {
        appLogger.Error("Database connection failed: %v", err)
        appLogger.Fatal("Cannot start without database")
    }
    appLogger.Success("Database connected")
    
    appLogger.Info("Application ready")
}

Color Output

When colors are enabled, each log level has its distinct color:

  • VERBOSE: Gray
  • DEBUG: Cyan
  • INFO: Blue
  • SUCCESS: Green
  • WARNING: Yellow
  • ERROR: Red
  • FATAL: Red

Colors automatically reset after each message to prevent affecting other terminal output.

Log Format

The default log format is:

[TIMESTAMP] [PREFIX] [LEVEL] MESSAGE

Example output:

[2024-01-15 14:30:25] [APP] [INFO] Server starting on port 8080
[2024-01-15 14:30:25] [APP] [SUCCESS] Database connection established
[2024-01-15 14:30:26] [APP] [WARNING] High memory usage detected: 85%
[2024-01-15 14:30:27] [APP] [ERROR] Failed to send notification email

Best Practices

  1. Use appropriate log levels: Don't use ERROR for non-error conditions
  2. Set proper log levels for environments: VERBOSE/DEBUG for development, INFO+ for production
  3. Use prefixes for different components: Makes it easier to filter logs
  4. Disable colors in production: Better for log aggregation systems
  5. Use Fatal sparingly: Only for conditions that require immediate program termination
  6. Format messages properly: Use format strings for dynamic content

Thread Safety

The logger is safe for concurrent use. Multiple goroutines can call logging methods simultaneously without additional synchronization.

Performance

The logger is designed to be fast and efficient:

  • Log level checking happens before message formatting
  • Color codes are applied only when needed
  • Minimal memory allocations for formatted messages

License

This logger package is provided as-is for educational and development purposes.

About

The logger package (github.com/hoanle396/logger) is a Go logging utility that provides structured logging capabilities with customizable prefixes and multiple log levels.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages