fancylog

package module
v0.0.23 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: MIT Imports: 11 Imported by: 0

README

fancylog provides stylized, non-blocking log output. It is designed to be fast, visually appealing, and highly configurable. It is used across many Golang projects here at NASK.

Features

  • Extremely Fast: Optimized for performance with minimal overhead.
  • Non-blocking: Designed to handle high-throughput logging without slowing down your application.
  • Visual Clarity: Uses ANSI colors to distinguish between different log levels and components.
  • Structured Logging: Supports logging maps and structured data for better machine readability.
  • Specialized HTTP Logging: Includes a dedicated logger for HTTP requests with status code coloring.
  • Middleware Support: Easy integration with Gin, gRPC, pgx, and standard net/http.
  • Customizable: Configure names, timestamps, colors, and more.

Installation

go get github.com/n-ask/fancylog

Quick Start

Basic Logging

package main

import (
    "os"
    "github.com/n-ask/fancylog"
)

func main() {
    // Create a new logger with os.Stdout as output
    log := fancylog.New(os.Stdout)

    log.Info("Starting application...")
    log.Warn("This is a warning message.")
    log.Error("Something went wrong!")
    
    // Structured logging with maps
    log.InfoMap(map[string]any{
        "event": "user_login",
        "user_id": 123,
        "status": "success",
    })
}

HTTP Logging

package main

import (
    "os"
    "github.com/n-ask/fancylog"
)

func main() {
    // Create a specialized HTTP logger
    httpLog := fancylog.NewHttpLogger(os.Stdout)

    // Log an HTTP GET request with a 200 OK status
    httpLog.GetMethod(map[string]any{
        "uri": "/api/v1/users",
        "ip": "127.0.0.1",
    }, 200)

    // Log an error status
    httpLog.PostMethod(map[string]any{
        "uri": "/api/v1/login",
    }, 401)
}

Integration with Frameworks

Gin Middleware

import (
    "github.com/gin-gonic/gin"
    "github.com/n-ask/fancylog"
    "github.com/n-ask/fancylog/handlers"
)

r := gin.New()
log := fancylog.NewHttpLogger(os.Stdout)
r.Use(handlers.GinLogger(log))

gRPC Interceptors

import (
    "google.golang.org/grpc"
    "github.com/n-ask/fancylog"
    "github.com/n-ask/fancylog/handlers"
)

log := fancylog.New(os.Stdout)
s := grpc.NewServer(
    grpc.UnaryInterceptor(handlers.UnaryServerInterceptor(log, fancylog.Info, myLogFunc, nil)),
)

Configuration

FancyLogger provides several methods to customize its behavior:

  • WithColor() / WithoutColor(): Enable or disable ANSI colors.
  • WithDebug() / WithoutDebug(): Show or hide debug and trace level logs.
  • WithTimestamp() / WithoutTimestamp(): Enable or disable timestamps.
  • Quiet() / NoQuiet(): Silence all output or resume logging.
  • SetTimestampColor(color): Customize the color of the timestamp.
  • NewWithName(name, output): Create a logger with a specific prefix name.

Documentation

Overview

Package fancylog provides stylized, non-blocking log output. It is designed to be fast and visually appealing with support for colors and structured logging via maps.

Index

Constants

View Source
const DepthSkip = 3

Variables

View Source
var (

	// Get retrieves a buffer from the pool, creating one if necessary.
	Get = _pool.Get
)
View Source
var HttpPrefixes = map[Level]Prefix{
	GetLevel: {
		Text:  GetLevel,
		Color: ColorCyan,
	},
	DeleteLevel: {
		Text:  DeleteLevel,
		Color: ColorCyan,
	},
	ConnectLevel: {
		Text:  ConnectLevel,
		Color: ColorCyan,
	},
	HeadLevel: {
		Text:  HeadLevel,
		Color: ColorCyan,
	},
	OptionsLevel: {
		Text:  OptionsLevel,
		Color: ColorCyan,
	},
	PostLevel: {
		Text:  PostLevel,
		Color: ColorCyan,
	},
	PutLevel: {
		Text:  PutLevel,
		Color: ColorCyan,
	},
	TraceLevel: {
		Text:  TraceLevel,
		Color: ColorCyan,
	},
}

HttpPrefixes maps HTTP levels to their corresponding Prefix configuration.

View Source
var Prefixes = map[Level]Prefix{
	Fatal: {
		Text:  Fatal,
		Color: ColorFatalRed,
		File:  true,
	},
	Error: {
		Text:  Error,
		Color: ColorRed,
	},
	Warn: {
		Text:  Warn,
		Color: ColorOrange,
	},
	Info: {
		Text:  Info,
		Color: ColorGreen,
	},
	Trace: {
		Text:  Trace,
		Color: ColorCyan,
		File:  true,
	},
	Debug: {
		Text:  Debug,
		Color: ColorPurple,
	},
}

Prefixes maps each Level to its corresponding Prefix configuration.

Functions

func Blue

func Blue(data []byte) []byte

Blue wraps the data in blue color escape sequences.

func Cyan

func Cyan(data []byte) []byte

Cyan wraps the data in cyan color escape sequences.

func Gray

func Gray(data []byte) []byte

Gray wraps the data in gray color escape sequences.

func Green

func Green(data []byte) []byte

Green wraps the data in green color escape sequences.

func Orange

func Orange(data []byte) []byte

Orange wraps the data in orange color escape sequences.

func Purple

func Purple(data []byte) []byte

Purple wraps the data in purple color escape sequences.

func Red

func Red(data []byte) []byte

Red wraps the data in red color escape sequences.

Types

type Color

type Color []byte

Color represents an ANSI color escape sequence as a byte slice.

var (
	ColorRed    Color = []byte("\u001B[0;31m")
	ColorGreen  Color = []byte("\u001B[0;32m")
	ColorOrange Color = []byte("\u001B[0;33m")
	ColorBlue   Color = []byte("\u001B[0;34m")
	ColorPurple Color = []byte("\u001B[0;35m")
	ColorCyan   Color = []byte("\u001B[0;36m")
	ColorGray   Color = []byte("\u001B[0;37m")

	// ColorFatalRed is a special color for fatal errors (bold, red background).
	ColorFatalRed    Color = []byte("\u001b[1m\u001b[31m\u001b[7m")
	ColorDarkOrange  Color = []byte("\u001b[1m\u001b[38;5;202m")
	ColorBrightWhite Color = []byte("\u001b[1m\u001b[38;5;255m")
	ColorNicePurple  Color = []byte("\u001b[1m\u001b[38;5;99m")
)

func UncheckedCustomColor

func UncheckedCustomColor(b []byte) Color

UncheckedCustomColor creates a custom Color from a byte slice without validation.

type ColorLogger

type ColorLogger struct {
	*buffer.Buffer
}

ColorLogger is a wrapper around a pooled buffer for efficient log message construction with colors.

func NewColorLogger

func NewColorLogger() ColorLogger

NewColorLogger creates a new ColorLogger instance using a buffer from the pool.

func (*ColorLogger) Append

func (cb *ColorLogger) Append(data []byte)

Append appends a byte slice to the buffer.

func (*ColorLogger) AppendSpace

func (cb *ColorLogger) AppendSpace()

AppendSpace appends a single space to the buffer.

func (*ColorLogger) AppendWithColor

func (cb *ColorLogger) AppendWithColor(data []byte, color Color)

AppendWithColor appends a byte slice to the buffer wrapped with color escape sequences.

func (*ColorLogger) Blue

func (cb *ColorLogger) Blue()

Blue applies blue color to the subsequent data.

func (*ColorLogger) BrightOrange

func (cb *ColorLogger) BrightOrange()

BrightOrange applies dark orange color to the subsequent data.

func (*ColorLogger) Cyan

func (cb *ColorLogger) Cyan()

Cyan applies cyan color to the subsequent data.

func (*ColorLogger) Gray

func (cb *ColorLogger) Gray()

Gray applies gray color to the subsequent data.

func (*ColorLogger) Green

func (cb *ColorLogger) Green()

Green applies green color to the subsequent data.

func (*ColorLogger) NicePurple

func (cb *ColorLogger) NicePurple()

NicePurple applies a "nice" purple color to the subsequent data.

func (*ColorLogger) Off

func (cb *ColorLogger) Off()

Off resets the color to the terminal default.

func (*ColorLogger) Orange

func (cb *ColorLogger) Orange()

Orange applies orange color to the subsequent data.

func (*ColorLogger) Purple

func (cb *ColorLogger) Purple()

Purple applies purple color to the subsequent data.

func (*ColorLogger) Red

func (cb *ColorLogger) Red()

Red applies red color to the subsequent data.

func (*ColorLogger) White

func (cb *ColorLogger) White()

White applies bright white color to the subsequent data.

func (*ColorLogger) WriteColor

func (cb *ColorLogger) WriteColor(color Color)

WriteColor applies the given color to the subsequent data.

type FancyHttpLog added in v0.0.13

type FancyHttpLog interface {
	FancyLogger
	Methods

	// WithHeaders enables logging of HTTP headers.
	WithHeaders() FancyHttpLog
	// DebugHeaders returns true if header logging is enabled.
	DebugHeaders() bool
}

FancyHttpLog is an extension of FancyLogger specialized for HTTP request logging. It includes methods for logging various HTTP methods with status codes.

func NewHttpLogger added in v0.0.11

func NewHttpLogger(out FdWriter) FancyHttpLog

NewHttpLogger returns a new HttpLog instance with a predefined writer output.

func NewHttpLoggerWithError added in v0.0.11

func NewHttpLoggerWithError(out FdWriter, err FdWriter) FancyHttpLog

NewHttpLoggerWithError returns a new HttpLog instance with separate writers for standard and error output.

func NewHttpLoggerWithName added in v0.0.11

func NewHttpLoggerWithName(name string, out FdWriter) FancyHttpLog

NewHttpLoggerWithName returns a new HttpLog instance with a specific name and writer output.

func NewHttpLoggerWithNameAndError added in v0.0.11

func NewHttpLoggerWithNameAndError(name string, out FdWriter, err FdWriter) FancyHttpLog

NewHttpLoggerWithNameAndError returns a new HttpLog instance with a specific name and separate writers for standard and error output.

type FancyLogger added in v0.0.11

type FancyLogger interface {
	StandardLog
	FormatLog
	MappedLog
	PrefixLog

	// WithColor explicitly enables colorful features on the log.
	WithColor() FancyLogger
	// WithoutColor explicitly disables colorful features on the log.
	WithoutColor() FancyLogger
	// WithDebug enables debugging output to reveal debug and trace level logs.
	WithDebug() FancyLogger
	// WithoutDebug disables debugging output.
	WithoutDebug() FancyLogger
	// WithTrace enables trace output to reveal trace level logs.
	WithTrace() FancyLogger
	// WithoutTrace disables trace output.
	WithoutTrace() FancyLogger
	// IsDebug checks the current state of debugging output.
	IsDebug() bool
	// IsTrace checks the current state of trace output.
	IsTrace() bool
	// WithTimestamp enables timestamp output on the log.
	WithTimestamp() FancyLogger
	// WithoutTimestamp disables timestamp output on the log.
	WithoutTimestamp() FancyLogger
	// Quiet disables all log output.
	Quiet() FancyLogger
	// NoQuiet enables all log output (disables quiet mode).
	NoQuiet() FancyLogger
	// IsQuiet checks if the logger is in quiet mode.
	IsQuiet() bool
	// HasColor checks if the logger has color enabled.
	HasColor() bool
	// contains filtered or unexported methods
}

FancyLogger is the primary interface for the fancylogger. It combines standard logging, formatted logging, mapped logging, and prefixed logging. It also provides configuration methods for colors, debug/trace levels, and quiet mode.

type FdWriter

type FdWriter interface {
	io.Writer
	Fd() uintptr
}

FdWriter interface extends existing io.Writer with file descriptor function support. This is typically implemented by os.File (like os.Stdout and os.Stderr).

type FormatLog added in v0.0.11

type FormatLog interface {
	Infof(format string, a ...any)
	Debugf(format string, a ...any)
	Warnf(format string, a ...any)
	Errorf(format string, a ...any)
	Tracef(format string, a ...any)
	Fatalf(format string, a ...any)
}

FormatLog defines the formatted logging methods (printf-style) for different severity levels.

type HttpLog added in v0.0.11

type HttpLog struct {
	FancyLogger
	// contains filtered or unexported fields
}

HttpLog implements the FancyHttpLog interface.

func (*HttpLog) ConnectMethod added in v0.0.13

func (h *HttpLog) ConnectMethod(a map[string]any, status int)

ConnectMethod logs a CONNECT request with structured data and status code.

func (*HttpLog) DebugHeaders added in v0.0.13

func (h *HttpLog) DebugHeaders() bool

DebugHeaders returns whether header logging is enabled.

func (*HttpLog) DeleteMethod added in v0.0.13

func (h *HttpLog) DeleteMethod(a map[string]any, status int)

DeleteMethod logs a DELETE request with structured data and status code.

func (*HttpLog) GetMethod added in v0.0.13

func (h *HttpLog) GetMethod(a map[string]any, status int)

GetMethod logs a GET request with structured data and status code.

func (*HttpLog) HeadMethod added in v0.0.13

func (h *HttpLog) HeadMethod(a map[string]any, status int)

HeadMethod logs a HEAD request with structured data and status code.

func (*HttpLog) OptionsMethod added in v0.0.13

func (h *HttpLog) OptionsMethod(a map[string]any, status int)

OptionsMethod logs an OPTIONS request with structured data and status code.

func (*HttpLog) PostMethod added in v0.0.13

func (h *HttpLog) PostMethod(a map[string]any, status int)

PostMethod logs a POST request with structured data and status code.

func (*HttpLog) PutMethod added in v0.0.13

func (h *HttpLog) PutMethod(a map[string]any, status int)

PutMethod logs a PUT request with structured data and status code.

func (*HttpLog) TraceMethod added in v0.0.13

func (h *HttpLog) TraceMethod(a map[string]any, status int)

TraceMethod logs a TRACE request with structured data and status code.

func (*HttpLog) WithHeaders added in v0.0.13

func (h *HttpLog) WithHeaders() FancyHttpLog

WithHeaders enables header logging for this HttpLog instance.

type Level added in v0.0.4

type Level string

Level represents the severity level of a log message.

const (
	// Fatal level indicates a critical error that will cause the application to exit.
	Fatal Level = "FATAL"
	// Error level indicates a significant problem that needs attention.
	Error Level = "ERROR"
	// Warn level indicates a potential issue or important situation.
	Warn Level = "WARN"
	// Info level indicates general informational messages.
	Info Level = "INFO"
	// Debug level indicates detailed information for troubleshooting.
	Debug Level = "DEBUG"
	// Trace level indicates even more granular information than Debug, often including stack traces.
	Trace Level = "TRACE"
)
const (
	// GetLevel represents the GET HTTP method.
	GetLevel Level = "GET"
	// DeleteLevel represents the DELETE HTTP method.
	DeleteLevel Level = "DELETE"
	// ConnectLevel represents the CONNECT HTTP method.
	ConnectLevel Level = "CONNECT"
	// HeadLevel represents the HEAD HTTP method.
	HeadLevel Level = "HEAD"
	// OptionsLevel represents the OPTIONS HTTP method.
	OptionsLevel Level = "OPTIONS"
	// PostLevel represents the POST HTTP method.
	PostLevel Level = "POST"
	// PutLevel represents the PUT HTTP method.
	PutLevel Level = "PUT"
	// TraceLevel represents the TRACE HTTP method.
	TraceLevel Level = "TRACE"
)

type Logger

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

Logger struct defines the underlying storage for a single logger instance.

func New

func New(out FdWriter) *Logger

New returns a new Logger instance with a predefined writer output. It automatically detects if the terminal supports coloring.

func NewWithError

func NewWithError(out FdWriter, err FdWriter) *Logger

NewWithError returns a new Logger instance with separate writers for standard and error output. It automatically detects if the terminal supports coloring. 'out' would typically be os.Stdout and 'err' would be os.Stderr.

func NewWithName

func NewWithName(name string, out FdWriter) *Logger

NewWithName returns a new Logger instance with a specific name and writer output. The name is used as a prefix for all log messages.

func NewWithNameAndError

func NewWithNameAndError(name string, out FdWriter, err FdWriter) *Logger

NewWithNameAndError returns a new Logger instance with a specific name and separate writers for standard and error output.

func (*Logger) Debug

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

Debug prints a debug message to the output if debug output is enabled.

func (*Logger) DebugMap

func (l *Logger) DebugMap(v map[string]interface{})

DebugMap logs structured debug data if debug output is enabled.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...interface{})

Debugf prints a formatted debug message to the output if debug output is enabled.

func (*Logger) Error

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

Error prints an error message to the output.

func (*Logger) ErrorMap

func (l *Logger) ErrorMap(v map[string]interface{})

ErrorMap logs structured error data.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...interface{})

Errorf prints a formatted error message to the output.

func (*Logger) Fatal

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

Fatal prints a fatal message to the output and exits the application with status 1.

func (*Logger) FatalMap

func (l *Logger) FatalMap(v map[string]interface{})

FatalMap logs structured fatal data and exits the application with status 1.

func (*Logger) FatalMapWithCode

func (l *Logger) FatalMapWithCode(exit int, v map[string]interface{})

FatalMapWithCode logs structured fatal data and exits the application with the provided status code.

func (*Logger) FatalWithCode

func (l *Logger) FatalWithCode(exit int, v ...interface{})

FatalWithCode prints a fatal message to the output and exits the application with the provided status code.

func (*Logger) FatalWithCodef

func (l *Logger) FatalWithCodef(format string, exit int, v ...interface{})

FatalWithCodef prints a formatted fatal message to the output and exits the application with the provided status code.

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...interface{})

Fatalf prints a formatted fatal message to the output and exits the application with status 1.

func (*Logger) HasColor added in v0.0.21

func (l *Logger) HasColor() bool

HasColor returns true if color output is enabled for this logger.

func (*Logger) Info

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

Info prints an informational message to the output.

func (*Logger) InfoMap

func (l *Logger) InfoMap(v map[string]interface{})

InfoMap logs structured informational data.

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof prints a formatted informational message to the output.

func (*Logger) IsDebug

func (l *Logger) IsDebug() bool

IsDebug checks the current state of debugging output.

func (*Logger) IsQuiet

func (l *Logger) IsQuiet() bool

IsQuiet checks if the logger is in quiet mode.

func (*Logger) IsTrace

func (l *Logger) IsTrace() bool

IsTrace checks the current state of trace output.

func (*Logger) Log added in v0.0.11

func (l *Logger) Log(prefix Prefix, a ...any)

Log prints a message with a custom prefix.

func (*Logger) LogMap added in v0.0.11

func (l *Logger) LogMap(prefix Prefix, a map[string]any)

LogMap logs structured data with a custom prefix.

func (*Logger) Logf added in v0.0.11

func (l *Logger) Logf(prefix Prefix, format string, a ...any)

Logf prints a formatted message with a custom prefix.

func (*Logger) NoQuiet

func (l *Logger) NoQuiet() FancyLogger

NoQuiet enables all log output (disables quiet mode).

func (*Logger) Quiet

func (l *Logger) Quiet() FancyLogger

Quiet disables all log output.

func (*Logger) SetDefaultTimeFn

func (l *Logger) SetDefaultTimeFn(timestampFunc TimestampFunc)

SetDefaultTimeFn overrides the default timestamp producer.

func (*Logger) SetTimestampColor

func (l *Logger) SetTimestampColor(color Color)

SetTimestampColor overrides the default color for timestamps.

func (*Logger) Trace

func (l *Logger) Trace(v ...interface{})

Trace prints a trace message to the output if trace output is enabled.

func (*Logger) TraceMap

func (l *Logger) TraceMap(v map[string]interface{})

TraceMap logs structured trace data if trace output is enabled.

func (*Logger) Tracef

func (l *Logger) Tracef(format string, v ...interface{})

Tracef prints a formatted trace message to the output if trace output is enabled.

func (*Logger) Warn

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

Warn prints a warning message to the output.

func (*Logger) WarnMap

func (l *Logger) WarnMap(v map[string]interface{})

WarnMap logs structured warning data.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...any)

Warnf prints a formatted warning message to the output.

func (*Logger) WithColor

func (l *Logger) WithColor() FancyLogger

WithColor explicitly enables colorful features on the log.

func (*Logger) WithDebug

func (l *Logger) WithDebug() FancyLogger

WithDebug enables debugging output to reveal debug and trace level logs.

func (*Logger) WithTimestamp

func (l *Logger) WithTimestamp() FancyLogger

WithTimestamp enables timestamp output on the log.

func (*Logger) WithTrace

func (l *Logger) WithTrace() FancyLogger

WithTrace enables trace output to reveal trace level logs.

func (*Logger) WithoutColor

func (l *Logger) WithoutColor() FancyLogger

WithoutColor explicitly disables colorful features on the log.

func (*Logger) WithoutDebug

func (l *Logger) WithoutDebug() FancyLogger

WithoutDebug disables debugging output.

func (*Logger) WithoutTimestamp

func (l *Logger) WithoutTimestamp() FancyLogger

WithoutTimestamp disables timestamp output on the log.

func (*Logger) WithoutTrace

func (l *Logger) WithoutTrace() FancyLogger

WithoutTrace disables trace output.

type MappedLog added in v0.0.11

type MappedLog interface {
	InfoMap(a map[string]any)
	DebugMap(a map[string]any)
	WarnMap(a map[string]any)
	ErrorMap(a map[string]any)
	TraceMap(a map[string]any)
	FatalMap(a map[string]any)
}

MappedLog defines the methods for logging structured data using maps.

type Methods added in v0.0.11

type Methods interface {
	GetMethod(a map[string]any, status int)
	DeleteMethod(a map[string]any, status int)
	ConnectMethod(a map[string]any, status int)
	HeadMethod(a map[string]any, status int)
	OptionsMethod(a map[string]any, status int)
	PostMethod(a map[string]any, status int)
	PutMethod(a map[string]any, status int)
	TraceMethod(a map[string]any, status int)
}

Methods defines the logging methods for different HTTP verbs.

type Prefix

type Prefix struct {
	Text  Level
	Color Color
	File  bool
}

Prefix struct defines the visual representation of a log level. Text will be the prefix text included in the log. Color will be the color applied to the log prefix. File flag set to true will display code trace (stack trace).

type PrefixLog added in v0.0.11

type PrefixLog interface {
	Log(prefix Prefix, a ...any)
	Logf(prefix Prefix, format string, a ...any)
	LogMap(prefix Prefix, a map[string]any)
}

PrefixLog defines methods for logging with custom prefixes.

type PrefixText added in v0.0.11

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

PrefixText struct holds the values of the prefixes to be used and the tail size to add spaces to the end of the prefix for alignment.

type StandardLog added in v0.0.11

type StandardLog interface {
	Info(a ...any)
	Debug(a ...any)
	Warn(a ...any)
	Error(a ...any)
	Trace(a ...any)
	Fatal(a ...any)
}

StandardLog defines the standard logging methods for different severity levels.

type TimestampFunc

type TimestampFunc func() (time time.Time, layout string)

TimestampFunc is a function type used to generate timestamps for log entries.

Directories

Path Synopsis
Package handlers provides middleware and helper functions for integrating fancylog with various frameworks and libraries like Gin, net/http, and pgx.
Package handlers provides middleware and helper functions for integrating fancylog with various frameworks and libraries like Gin, net/http, and pgx.

Jump to

Keyboard shortcuts

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