Convert Figma logo to code with AI

inconshreveable logolog15

Structured, composable logging for Go

1,103
145
1,103
45

Top Related Projects

24,520

Structured, pluggable logging for Go.

10,371

Zero Allocation JSON Logger

21,647

Blazing fast, structured, leveled logging in Go.

1,362

Structured logging package for Go.

lumberjack is a log rolling package for Go

3,525

Leveled execution logs for Go

Quick Overview

Log15 is a powerful, flexible, and structured logging library for Go. It provides a simple, extensible API that allows developers to add context to their logs and create custom logging handlers easily. Log15 is designed to be fast and efficient, making it suitable for both development and production environments.

Pros

  • Structured logging with key-value pairs for easy filtering and analysis
  • Flexible and extensible architecture allowing custom handlers and formatters
  • Support for multiple output formats (JSON, logfmt, terminal)
  • Excellent performance with minimal allocations

Cons

  • Not as widely adopted as some other logging libraries in the Go ecosystem
  • Limited built-in integrations with third-party services
  • May require more setup compared to simpler logging libraries
  • Documentation could be more comprehensive

Code Examples

  1. Basic logging:
import "github.com/inconshreveable/log15"

log := log15.New()
log.Info("Hello, world!", "user", "Alice", "status", "active")
  1. Creating a custom logger with context:
logger := log15.New("module", "app", "version", "1.0")
logger.Debug("Starting application", "port", 8080)
  1. Using a file handler:
import "os"

file, _ := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
handler := log15.StreamHandler(file, log15.JsonFormat())
logger := log15.New()
logger.SetHandler(handler)
  1. Creating a multi-handler setup:
consoleHandler := log15.StreamHandler(os.Stdout, log15.TerminalFormat())
fileHandler := log15.Must.FileHandler("app.log", log15.JsonFormat())
multiHandler := log15.MultiHandler(consoleHandler, fileHandler)

logger := log15.New()
logger.SetHandler(multiHandler)

Getting Started

To start using Log15 in your Go project, follow these steps:

  1. Install the library:

    go get github.com/inconshreveable/log15
    
  2. Import the package in your Go file:

    import "github.com/inconshreveable/log15"
    
  3. Create a new logger and start logging:

    log := log15.New()
    log.Info("Application started", "version", "1.0", "env", "production")
    
  4. Customize the logger as needed, adding handlers or formatters to suit your requirements.

Competitor Comparisons

24,520

Structured, pluggable logging for Go.

Pros of Logrus

  • More popular and widely adopted in the Go community
  • Offers a wider range of built-in formatters (JSON, text, etc.)
  • Supports hooks for easy integration with external logging services

Cons of Logrus

  • Slightly more complex API compared to Log15
  • Performance can be slower in some scenarios, especially with many fields

Code Comparison

Log15:

log.Info("starting up", "protocol", "http", "port", 8080)

Logrus:

logrus.WithFields(logrus.Fields{
    "protocol": "http",
    "port":     8080,
}).Info("starting up")

Key Differences

  • Log15 uses a simpler, more concise syntax for structured logging
  • Logrus provides more flexibility in terms of formatting and output options
  • Log15 focuses on performance and simplicity, while Logrus offers more features and integrations

Use Cases

  • Log15: Ideal for projects prioritizing simplicity and performance
  • Logrus: Better suited for complex applications requiring extensive logging features and integrations

Both libraries are well-maintained and offer structured logging capabilities for Go applications. The choice between them often depends on specific project requirements and personal preferences.

10,371

Zero Allocation JSON Logger

Pros of zerolog

  • Higher performance and lower allocation overhead
  • Supports JSON logging out of the box
  • More flexible and customizable API

Cons of zerolog

  • Steeper learning curve due to its unique API design
  • Less built-in functionality for log levels and contexts

Code Comparison

log15:

log.Info("message", "key1", value1, "key2", value2)

zerolog:

log.Info().
    Str("key1", value1).
    Int("key2", value2).
    Msg("message")

Summary

zerolog offers superior performance and JSON logging capabilities, making it ideal for high-throughput applications. Its chainable API provides great flexibility but may require more effort to learn. log15, on the other hand, has a simpler API and built-in features for log levels and contexts, which can be beneficial for smaller projects or developers who prefer a more straightforward approach.

Both libraries have their strengths, and the choice between them depends on specific project requirements, performance needs, and developer preferences. zerolog is better suited for performance-critical applications, while log15 might be more appropriate for projects prioritizing simplicity and ease of use.

21,647

Blazing fast, structured, leveled logging in Go.

Pros of zap

  • Higher performance and lower allocation overhead
  • Structured logging with type-safe field constructors
  • More flexible configuration options and log levels

Cons of zap

  • Steeper learning curve due to more complex API
  • Requires more setup code for basic usage
  • Less intuitive for developers familiar with traditional logging patterns

Code Comparison

log15:

log.Info("User logged in", "user", user.Name, "admin", user.IsAdmin)

zap:

logger.Info("User logged in",
    zap.String("user", user.Name),
    zap.Bool("admin", user.IsAdmin),
)

Both libraries support structured logging, but zap requires explicit type declarations for fields. log15 uses a simpler key-value pair approach, while zap offers more type safety and performance optimizations at the cost of verbosity.

zap generally provides better performance and more advanced features, but log15 offers a simpler API that may be easier for some developers to adopt quickly. The choice between them depends on specific project requirements, performance needs, and team preferences.

1,362

Structured logging package for Go.

Pros of apex/log

  • Simpler API with fewer concepts to learn
  • Built-in support for AWS Lambda and other cloud environments
  • More actively maintained with recent updates

Cons of apex/log

  • Less flexible configuration options
  • Fewer built-in handlers and formatters
  • Limited support for custom log levels

Code Comparison

log15:

log.Info("starting up", "listen", ":8080")
log.Warn("deprecated feature used", "feature", "X", "alternative", "Y")
log.Crit("failed to start", "err", err)

apex/log:

log.Info("starting up")
log.WithField("listen", ":8080").Info("server listening")
log.WithFields(log.Fields{
    "feature": "X",
    "alternative": "Y",
}).Warn("deprecated feature used")

Both libraries offer structured logging, but log15 allows for more compact inline field definitions, while apex/log uses method chaining for field addition. apex/log's approach may be more readable for complex log entries, but log15's style is more concise for simple logs.

lumberjack is a log rolling package for Go

Pros of Lumberjack

  • Simple and lightweight, focusing on log rotation and management
  • Easy integration with Go's standard library log package
  • Supports log file compression

Cons of Lumberjack

  • Limited features compared to more comprehensive logging frameworks
  • Lacks built-in structured logging capabilities
  • No support for multiple output destinations

Code Comparison

Lumberjack:

log.SetOutput(&lumberjack.Logger{
    Filename:   "/var/log/myapp/foo.log",
    MaxSize:    500, // megabytes
    MaxBackups: 3,
    MaxAge:     28, // days
    Compress:   true, // disabled by default
})

Log15:

log.Root().SetHandler(log.MultiHandler(
    log.StreamHandler(os.Stderr, log.LogfmtFormat()),
    log.LvlFilterHandler(
        log.LvlInfo,
        log.Must.FileHandler("errors.json", log.JsonFormat()),
    ),
))

Log15 offers a more flexible and feature-rich logging solution with structured logging, multiple handlers, and customizable formatting. Lumberjack, on the other hand, focuses specifically on log file rotation and management, making it a simpler choice for projects that primarily need this functionality. Log15 provides more advanced logging capabilities, while Lumberjack integrates seamlessly with Go's standard library for basic logging needs with added file management features.

3,525

Leveled execution logs for Go

Pros of glog

  • Widely used and battle-tested in Google's production environments
  • Provides built-in support for command-line flags for easy configuration
  • Offers automatic log file rotation and management

Cons of glog

  • Less flexible and customizable compared to log15
  • Lacks structured logging capabilities out of the box
  • Limited support for different output formats and destinations

Code Comparison

glog:

import "github.com/golang/glog"

glog.Info("Informational message")
glog.Errorf("Error: %v", err)
glog.V(2).Infoln("Verbose message")

log15:

import "github.com/inconshreveable/log15"

log := log15.New()
log.Info("Informational message")
log.Error("Error occurred", "err", err)
log.Debug("Debug message", "key1", value1, "key2", value2)

Key Differences

  • glog uses a global logger instance, while log15 encourages creating logger instances
  • log15 supports structured logging with key-value pairs, making it more flexible for complex logging scenarios
  • glog's verbosity levels are controlled via command-line flags, whereas log15 allows for more programmatic control
  • log15 offers easier customization of log formats and output destinations

Both libraries have their strengths, with glog being more suitable for projects requiring simple, production-ready logging, and log15 offering greater flexibility and structured logging capabilities for more complex applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

obligatory xkcd

log15 godoc reference Build Status

Package log15 provides an opinionated, simple toolkit for best-practice logging in Go (golang) that is both human and machine readable. It is modeled after the Go standard library's io and net/http packages and is an alternative to the standard library's log package.

Features

  • A simple, easy-to-understand API
  • Promotes structured logging by encouraging use of key/value pairs
  • Child loggers which inherit and add their own private context
  • Lazy evaluation of expensive operations
  • Simple Handler interface allowing for construction of flexible, custom logging configurations with a tiny API.
  • Color terminal support
  • Built-in support for logging to files, streams, syslog, and the network
  • Support for forking records to multiple handlers, buffering records for output, failing over from failed handler writes, + more

Versioning

The API of the master branch of log15 should always be considered unstable. If you want to rely on a stable API, you must vendor the library.

Importing

import log "github.com/inconshreveable/log15"

Examples

// all loggers can have key/value context
srvlog := log.New("module", "app/server")

// all log messages can have key/value context
srvlog.Warn("abnormal conn rate", "rate", curRate, "low", lowRate, "high", highRate)

// child loggers with inherited context
connlog := srvlog.New("raddr", c.RemoteAddr())
connlog.Info("connection open")

// lazy evaluation
connlog.Debug("ping remote", "latency", log.Lazy{pingRemote})

// flexible configuration
srvlog.SetHandler(log.MultiHandler(
    log.StreamHandler(os.Stderr, log.LogfmtFormat()),
    log.LvlFilterHandler(
        log.LvlError,
        log.Must.FileHandler("errors.json", log.JsonFormat()))))

Will result in output that looks like this:

WARN[06-17|21:58:10] abnormal conn rate                       module=app/server rate=0.500 low=0.100 high=0.800
INFO[06-17|21:58:10] connection open                          module=app/server raddr=10.0.0.1

Breaking API Changes

The following commits broke API stability. This reference is intended to help you understand the consequences of updating to a newer version of log15.

  • 57a084d014d4150152b19e4e531399a7145d1540 - Added a Get() method to the Logger interface to retrieve the current handler
  • 93404652ee366648fa622b64d1e2b67d75a3094a - Record field Call changed to stack.Call with switch to github.com/go-stack/stack
  • a5e7613673c73281f58e15a87d2cf0cf111e8152 - Restored syslog.Priority argument to the SyslogXxx handler constructors

FAQ

The varargs style is brittle and error prone! Can I have type safety please?

Yes. Use log.Ctx:

srvlog := log.New(log.Ctx{"module": "app/server"})
srvlog.Warn("abnormal conn rate", log.Ctx{"rate": curRate, "low": lowRate, "high": highRate})

Regenerating the CONTRIBUTORS file

go get -u github.com/kevinburke/write_mailmap
write_mailmap > CONTRIBUTORS

License

Apache