# Gookit Slog

> Lightweight, structured, extensible logging library for Go

- Skill: `gookit/gookit-slog` (Agent Skill, multi-file: 5 files)
- Install (CLI): `npx skillmds@latest add gookit/gookit-slog`
- Raw SKILL.md: https://api.skillmd.com/api/skills/gookit/gookit-slog/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: gookit (https://skillmd.com/u/gookit)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/gookit/gookit-slog

---


# 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:**

```text
[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

```go
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

```go
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

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

slog.Info("colored log message")
```

### JSON Format

```go
// 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

```text
          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

```go
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

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

### Structured Logging

```go
// 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

```go
// 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

```go
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

```go
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

```go
// 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

```go
// 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:

```go
// 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:

```go
// 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](references/HANDLERS.md)** - All built-in handlers and configuration
- 🔧 **[Advanced Usage](references/ADVANCED.md)** - Custom handlers, formatters, processors, rotatefile
- 📝 **[Examples](references/EXAMPLES.md)** - 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

