gookit

gookit-slog

by @gookit in Tools
1
0
# Install this skill:
npx skills add gookit/skills --skill "gookit-slog"

Install specific skill from multi-skill repository

# Description

Lightweight, structured, extensible logging library for Go

# SKILL.md


name: gookit-slog
description: Lightweight, structured, extensible logging library for Go
author: auto-generated by repo2skill
platform: github
source: https://github.com/gookit/slog
tags: [go, logging, structured-logging, log-rotation, handlers, formatters]
version: 1.0.0
generated: 2026-01-28T00:00:00Z


slog - Structured Logging for Go

Lightweight, structured, extensible, and configurable logging library written in Golang.

Overview

slog is designed for simplicity and flexibility - works out of the box with zero configuration, yet powerful enough for complex logging needs.

Console Output:

[2020/07/16 12:19:33] [application] [INFO] [main.go:7] info log message
[2020/07/16 12:19:33] [application] [WARNING] [main.go:8] warning log message

Core Features

πŸš€ Zero Configuration

  • Works immediately without any setup
  • Sensible defaults for common scenarios
  • Easy to customize when needed

πŸ“Š Structured Logging

  • Support for 8 log levels: trace, debug, info, notice, warn, error, fatal, panic
  • Add contextual fields with WithFields(), WithData()
  • Multiple output formats: text, JSON

πŸ”Œ Extensible Architecture

  • Handler: Output logs to different destinations (console, file, syslog, email)
  • Formatter: Format logs as text or JSON
  • Processor: Add custom processing logic

πŸ“ File Logging

  • Write to single file or rotate by time/size
  • Buffer support for better performance
  • Gzip compression for old logs
  • Automatic cleanup of old files

🎨 Console Color

  • Colored output for different log levels
  • Easy to enable/disable

Quick Start

Basic Usage

package main

import "github.com/gookit/slog"

func main() {
    slog.Info("info log message")
    slog.Warn("warning log message")
    slog.Infof("info log %s", "message")
    slog.Debugf("debug %s", "message")
}

With Fields

slog.WithFields(slog.M{
    "user_id": 123,
    "action":  "login",
}).Info("user logged in")

// Or use WithData
slog.WithData(slog.M{
    "key": "value",
}).Warn("warning with context")

Enable Console Color

slog.Configure(func(logger *slog.SugaredLogger) {
    f := logger.Formatter.(*slog.TextFormatter)
    f.EnableColor = true
})

slog.Info("colored log message")

JSON Format

// Switch to JSON formatter
slog.SetFormatter(slog.NewJSONFormatter())

slog.Info("log as JSON")
// Output: {"channel":"application","level":"INFO","datetime":"2020/07/16 13:23:33","message":"log as JSON"}

Architecture

          Processors (add fields, modify records)
Logger ──{
          Handlers ──┬─ ConsoleHandler (with TextFormatter)
                     β”œβ”€ FileHandler (with JSONFormatter)
                     β”œβ”€ RotateFileHandler (with buffer)
                     └─ ... custom handlers

Components:

  • Logger: Dispatches log records to registered handlers
  • Record: Log entry with level, message, fields, timestamp
  • Processor: Processes records before handlers (add fields, etc.)
  • Handler: Outputs logs to destinations (console, file, etc.)
  • Formatter: Formats records (text template, JSON)

Basic Usage

Log Levels

slog.Trace("trace message")   // Most verbose
slog.Debug("debug message")
slog.Info("info message")
slog.Notice("notice message")
slog.Warn("warning message")
slog.Error("error message")
slog.Fatal("fatal message")   // Calls os.Exit(1)
slog.Panic("panic message")   // Calls panic()

Formatted Logging

slog.Infof("user %s logged in", username)
slog.Errorf("failed to connect: %v", err)

Structured Logging

// Create a logger with fields
logger := slog.WithFields(slog.M{
    "module": "auth",
    "env":    "prod",
})

logger.Info("authentication started")
logger.Error("authentication failed")

// Add temporary fields
logger.WithData(slog.M{
    "user_id": 123,
    "ip":      "192.168.1.1",
}).Warn("suspicious activity")

Custom Logger

// Create new logger instance
l := slog.New()

// Add handlers
h := handler.NewConsoleHandler(slog.AllLevels)
l.AddHandlers(h)

// Use it
l.Info("message from custom logger")

Configure Default Logger

slog.Configure(func(logger *slog.SugaredLogger) {
    // Change formatter
    f := logger.Formatter.(*slog.TextFormatter)
    f.EnableColor = true
    f.SetTemplate(slog.NamedTemplate)

    // Set log level
    logger.Level = slog.WarnLevel
})

Log to File

Simple File Handler

import "github.com/gookit/slog/handler"

// Write to file without buffer
h, err := handler.NewFileHandler("/var/log/app.log")
if err != nil {
    panic(err)
}

slog.AddHandlers(h)
defer slog.MustClose()

Buffered File Handler

// Write with buffer for better performance
h, err := handler.NewBuffFileHandler(
    "/var/log/app.log",
    1024*8, // 8KB buffer
)

slog.AddHandlers(h)
defer slog.MustClose() // Important: flush buffer

Rotate File Handler

// Rotate by time and size
h, err := handler.NewRotateFileHandler(
    "/var/log/app.log",
    rotatefile.EveryHour, // Rotate every hour
    handler.WithMaxSize(20*1024*1024), // 20MB max size
    handler.WithBackupNum(10),         // Keep 10 old files
    handler.WithCompress(true),        // Gzip old files
)

slog.AddHandlers(h)
defer slog.MustClose()

Multiple Handlers

Output different log levels to different files:

// Error logs to error.log
errorHandler := handler.MustFileHandler(
    "/var/log/error.log",
    handler.WithLogLevels(slog.DangerLevels), // panic, fatal, error, warn
)

// Info logs to info.log
infoHandler := handler.MustFileHandler(
    "/var/log/info.log",
    handler.WithLogLevels(slog.NormalLevels), // info, notice, debug, trace
)

slog.PushHandlers(errorHandler, infoHandler)
defer slog.MustClose()

slog.Info("goes to info.log")
slog.Error("goes to error.log")

Processors

Add custom processing to all log records:

// Built-in processor: add hostname
slog.AddProcessor(slog.AddHostname())

// Custom processor
slog.AddProcessor(slog.ProcessorFunc(func(record *slog.Record) {
    record.Extra["app_version"] = "1.0.0"
    record.Extra["env"] = os.Getenv("APP_ENV")
}))

slog.Info("message")
// Output includes: "hostname":"MyServer", "app_version":"1.0.0", "env":"production"

Documentation

  • πŸ“˜ Handlers Guide - All built-in handlers and configuration
  • πŸ”§ Advanced Usage - Custom handlers, formatters, processors, rotatefile
  • πŸ“ Examples - Real-world usage examples

Best Practices

  1. Always close loggers: Call slog.MustClose() or logger.Close() when using buffered handlers
  2. Use structured logging: Add context with WithFields() instead of formatting messages
  3. Separate log levels: Use different handlers for different log levels
  4. Rotate log files: Enable rotation for production applications
  5. Use processors wisely: Add common fields via processors, not in every log call

Resources

  • GitHub: https://github.com/gookit/slog
  • Go Package: https://pkg.go.dev/github.com/gookit/slog
  • δΈ­ζ–‡ζ–‡ζ‘£: https://github.com/gookit/slog/blob/master/README.zh-CN.md

# Supported AI Coding Agents

This skill is compatible with the SKILL.md standard and works with all major AI coding agents:

Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.