slog

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 14 Imported by: 2

README

slog

A simple, flexible, and feature-rich structured logging library for Go.

Features

  • Multiple log levels (Debug, Info, Warn, Error, Fatal, Panic, Stat)
  • Built-in default stdout logger with ANSI colors
  • Support for multiple writers (stdout, file, HTTP, and custom channels)
  • ANSI color formatting for terminal output
  • JSON support for structured logging
  • File rotation support
  • Buffer system for log management
  • Flexible argument handling with both standard and formatted logging
  • HTTP logging with API key support
  • Channel-based logging for custom log processing
  • Concurrent-safe logging

Installation

go get github.com/AR1011/slog

Basic Usage

The library comes with a default stdout logger, so you can start logging immediately:

package main

import "github.com/AR1011/slog"

func main() {
    // Basic logging
    slog.Debug("Debug message")
    slog.Info("Info message")
    slog.Warn("Warning message")
    slog.Error("Error message")
    
    // Logging with context
    slog.Info("User logged in", "user_id", 123, "ip", "192.168.1.1")
    
    // Format string logging
    slog.InfoF("User %s logged in from %s", []interface{}{"john", "192.168.1.1"})
    
    // Don't forget to close the logger when you're done
    defer slog.Close()
}

Log Levels

The library supports the following log levels:

  • Debug: Detailed information for debugging
  • Info: General information about program execution
  • Warn: Warning messages for potentially harmful situations
  • Error: Error messages for serious problems
  • Fatal: Critical errors that terminate the program
  • Panic: Critical errors that trigger a panic
  • Stat: Statistical or metric information

Writers

Stdout Writer

The stdout writer is the default writer, but you can configure it explicitly:

logger, _ := slog.NewLogger(slog.WithStdIoWriter(&slog.ToStdStreamWriterOptions{
    Stream: slog.StdOut,  // or slog.StdErr
    Format: slog.FormatAnsi,
    Level:  slog.DebugLevel,
}))
File Writer

Write logs to a file with optional rotation:

slog.AddWriter(slog.WithToFileWriter(&slog.ToFileWriterOptions{
    FileName:   "app.log",
    Format:     slog.FormatJson,
    Level:      slog.InfoLevel,
    RotateSize: 1024 * 1024 * 100, // 100MB
}))
HTTP Writer

Send logs to a remote endpoint:

slog.AddWriter(slog.WithToHttpWriter(&slog.ToHttpWriterOptions{
    URL:    "http://localhost:8080/logs",
    Method: "POST",
    Format: slog.FormatJson,
    Level:  slog.InfoLevel,
    APIKey: "your-api-key-here",
}))
Channel Writer

Process logs using a custom channel handler:

logChan := make(chan *slog.Log, 100)
logger, _ := slog.NewLogger(slog.WithToChanWriter(&slog.ToChanWriterOptions{
    Ch:    logChan,
    Level: slog.InfoLevel,
}))

// Process logs in a separate goroutine
go func() {
    for log := range logChan {
        // Custom log processing
        fmt.Printf("Custom handler: [%s] %s\n", log.Type, log.Msg)
    }
}()

Multiple Writers

You can combine multiple writers to send logs to different destinations:

logger, _ := slog.NewLogger(
    // Console output with ANSI colors
    slog.WithStdIoWriter(&slog.ToStdStreamWriterOptions{
        Stream: slog.StdOut,
        Format: slog.FormatAnsi,
        Level:  slog.DebugLevel,
    }),
    
    // JSON file output
    slog.WithToFileWriter(&slog.ToFileWriterOptions{
        FileName: "app.log",
        Format:  slog.FormatJson,
        Level:   slog.InfoLevel,
    }),
)

slog.SetLogger(logger)

Formatting Options

The library supports two main formatting options:

  • FormatAnsi: Colored output for terminal (default for stdout)
  • FormatJson: JSON structured logging (ideal for file and HTTP writers)

Examples

For more detailed examples, check out the examples directory:

  • examples/stdout/: Basic logging with stdout
  • examples/file/: File logging with rotation
  • examples/http/: Remote logging via HTTP
  • examples/channel/: Custom log processing with channels
  • examples/multiple/: Using multiple writers
  • examples/advanced/: Advanced usage patterns

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	ColorDarkBLue   = "\u001b[38;2;0;51;204m"
	ColorDarkGreen  = "\033[38;2;0;153;0m"
	ColorDarkPurple = "\033[38;2;102;0;153m"
	ColorGreen      = "\033[32m"
	ColorBlue       = "\033[34m"
	ColorRed        = "\033[31m"
	ColorOrange     = "\033[33m"
	ColorPurple     = "\033[35m"
	ColorYellow     = "\033[93m"
	ColorPink       = "\033[95m"
	ColorWhite      = "\033[0m"
	FontBold        = "\u001b[1m"
	FontNormal      = "\u001b[0m"
)
View Source
const (
	PadWidth = 50
	Truncate = false
)

Variables

This section is empty.

Functions

func AddWriter

func AddWriter(w Writer)

func Close

func Close()

func Debug

func Debug(msg string, args ...interface{})

func DebugF

func DebugF(format string, formatArgs []interface{}, args ...interface{})

func EncodeLogToInterface

func EncodeLogToInterface(l Log, f LogFormat) interface{}

func Error

func Error(msg string, args ...interface{})

func ErrorF

func ErrorF(format string, formatArgs []interface{}, args ...interface{})

func Fatal

func Fatal(msg string, args ...interface{})

func FatalF

func FatalF(format string, formatArgs []interface{}, args ...interface{})

func GetTime

func GetTime() string

func Info

func Info(msg string, args ...interface{})

func InfoF

func InfoF(format string, formatArgs []interface{}, args ...interface{})

func IsValidLogFormat

func IsValidLogFormat(s string) bool

func Panic

func Panic(msg string, args ...interface{})

func PanicF

func PanicF(format string, formatArgs []interface{}, args ...interface{})

func RemoveAnsiString

func RemoveAnsiString(s string) string

func SetLogger

func SetLogger(l *SLogger)

func Stat

func Stat(msg string, args ...interface{})

func Warn

func Warn(msg string, args ...interface{})

func WarnF

func WarnF(format string, formatArgs []interface{}, args ...interface{})

func WithStdIoWriter

func WithStdIoWriter(opt *ToStdStreamWriterOptions) *toStdStreamWriter

func WithToChanWriter

func WithToChanWriter(opt *ToChanWriterOptions) *toChanWriter

Types

type Log

type Log struct {
	Type      string                 `json:"level"`
	Level     LogLevel               `json:"-"`
	TypeColor string                 `json:"-"`
	Time      string                 `json:"time"`
	Timestamp time.Time              `json:"timestamp"`
	Msg       string                 `json:"msg"`
	MsgColor  string                 `json:"-"`
	Args      map[string]interface{} `json:"args"`
	ArgKeys   []string               `json:"-"`
	Str       string                 `json:"-"`
}

func (*Log) Copy

func (l *Log) Copy() Log

type LogBuffer

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

func NewLogBuffer

func NewLogBuffer(max int) *LogBuffer

func (*LogBuffer) Add

func (b *LogBuffer) Add(log *Log)

func (*LogBuffer) Clear

func (b *LogBuffer) Clear()

func (*LogBuffer) GetLogs

func (b *LogBuffer) GetLogs(limit int64) []Log

func (*LogBuffer) GetLogsInterface

func (b *LogBuffer) GetLogsInterface(limit int64, format LogFormat) ([]interface{}, int64)

type LogFormat

type LogFormat string
const (
	FormatJson LogFormat = "json"
	FormatText LogFormat = "text"
	FormatAnsi LogFormat = "ansi"
)

func ToLogFormat

func ToLogFormat(s string) LogFormat

type LogLevel

type LogLevel int
const (
	DebugLevel LogLevel = iota + 1
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
	PanicLevel
)

func ToLogLevel

func ToLogLevel(s string) LogLevel

type LogLevelString

type LogLevelString string
const (
	DebugLevelString LogLevelString = "debug"
	InfoLevelString  LogLevelString = "info"
	WarnLevelString  LogLevelString = "warn"
	ErrorLevelString LogLevelString = "error"
	FatalLevelString LogLevelString = "fatal"
	PanicLevelString LogLevelString = "panic"
)

type SLogger

type SLogger struct {
	Buffer *LogBuffer
	// contains filtered or unexported fields
}
var Slog *SLogger = &SLogger{
	Buffer: NewLogBuffer(1000),
	writers: []Writer{
		&toStdStreamWriter{
			Stream: StdOut,
			format: FormatAnsi,
			level:  InfoLevel,
		},
	},
}

set default logger

func NewLogger

func NewLogger(writers ...Writer) (*SLogger, error)

func (*SLogger) AddWriter

func (s *SLogger) AddWriter(w Writer)

func (*SLogger) Close

func (s *SLogger) Close()

type StdStream

type StdStream int
const (
	StdOut StdStream = iota
	StdErr
)

type ToChanWriterOptions

type ToChanWriterOptions struct {
	Level LogLevel
	Ch    chan *Log
}

type ToFileWriter

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

func WithToFileWriter

func WithToFileWriter(opt *ToFileWriterOptions) *ToFileWriter

func (*ToFileWriter) Close

func (w *ToFileWriter) Close()

func (*ToFileWriter) FileName

func (w *ToFileWriter) FileName() string

func (*ToFileWriter) Format

func (w *ToFileWriter) Format() LogFormat

func (*ToFileWriter) Level

func (w *ToFileWriter) Level() LogLevel

func (*ToFileWriter) Write

func (w *ToFileWriter) Write(l *Log) error

type ToFileWriterOptions

type ToFileWriterOptions struct {
	FileName   string
	Format     LogFormat
	Level      LogLevel
	RotateSize int64 // kB
}

type ToHttpWriter

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

func WithToHttpWriter

func WithToHttpWriter(opt *ToHttpWriterOptions) *ToHttpWriter

func (*ToHttpWriter) Close

func (w *ToHttpWriter) Close()

func (*ToHttpWriter) Level

func (w *ToHttpWriter) Level() LogLevel

func (*ToHttpWriter) Write

func (w *ToHttpWriter) Write(l *Log) error

type ToHttpWriterOptions

type ToHttpWriterOptions struct {
	Level  LogLevel
	Format LogFormat
	URL    string
	Method string
	APIKey string
}

type ToStdStreamWriterOptions

type ToStdStreamWriterOptions struct {
	Level  LogLevel
	Format LogFormat
	Stream StdStream
}

type Writer

type Writer interface {
	Level() LogLevel
	Write(*Log) error
	Close()
}

Directories

Path Synopsis
examples
advanced command
channel command
file command
http command
multiple command
stdout command

Jump to

Keyboard shortcuts

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