slog

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2019 License: MIT Imports: 16 Imported by: 0

README

slog

GoDoc GitHub release (latest SemVer) Codecov CI

slog is a minimal structured logging library for Go.

Install

go get go.coder.com/slog

Features

  • Minimal API
  • Tiny codebase
  • First class context.Context support
  • First class testing.TB support
  • Beautiful logging output by default
  • Multiple adapters

Example

slogtest.Info(t, "my message here",
    slog.F("field_name", "something or the other"),
    slog.F("some_map", slog.Map(
        slog.F("nested_fields", "wowow"),
    )),
    slog.Error(
        xerrors.Errorf("wrap1: %w",
            xerrors.Errorf("wrap2: %w",
                io.EOF),
        ),
    ),
)

Example output screenshot

Design justifications

See #9

Comparison

zap

https://github.com/uber-go/zap

See #6.

Contributing

See .github/CONTRIBUTING.md.

Users

If your company or project is using this library, feel free to open an issue or PR to amend this list.

Documentation

Overview

Package slog implements minimal structured logging.

Example (Test)
package main

import (
	"io"
	"testing"

	"golang.org/x/xerrors"

	"go.coder.com/slog"
	"go.coder.com/slog/sloggers/slogtest"
)

func main() {
	// Nil here but would be provided by the testing framework.
	var t testing.TB

	slogtest.Info(t, "my message here",
		slog.F("field_name", "something or the other"),
		slog.F("some_map", slog.Map(
			slog.F("nested_fields", "wowow"),
		)),
		slog.Error(
			xerrors.Errorf("wrap1: %w",
				xerrors.Errorf("wrap2: %w",
					io.EOF),
			),
		),
	)

	// t.go:55: 2019-09-13 23:19:03.468 [INFO]	<examples_test.go:43>	my message here	{"field_name": "something or the other", "some_map": {"nested_fields": "wowow"}} ...
	//     "error": wrap1:
	//         go.coder.com/slog_test.TestExample
	//             /Users/nhooyr/src/cdr/slog/examples_test.go:49
	//       - wrap2:
	//         go.coder.com/slog_test.TestExample
	//             /Users/nhooyr/src/cdr/slog/examples_test.go:50
	//       - EOF
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Context added in v0.1.0

func Context(ctx context.Context, fields ...Field) context.Context

Context returns a context that contains the given fields. Any logs written with the provided context will have the given logs prepended. It will append to any fields already in ctx.

func Encode added in v0.2.0

func Encode(v interface{}) slogval.Value

Encode encodes the interface to a structured and easily introspectable slogval.Value.

func JSON added in v0.2.0

func JSON(v interface{}) interface{}

JSON tells the encoder that the struct in v should be encoded obeying JSON struct tags. Field names can be adjusted and omitempty is obeyed.

func Stdlib

func Stdlib(ctx context.Context, l Logger) *log.Logger

Stdlib creates a standard library logger from the given logger.

All logs will be logged at the Info level and the given ctx will be passed to the logger's Info method, thereby logging all fields and tracing info in the context.

You can redirect the stdlib default logger with log.SetOutput to the Writer on the logger returned by this function. See the example.

Types

type Entry added in v0.1.0

type Entry struct {
	Time time.Time

	Level   Level
	Message string

	LoggerName string

	Func string
	File string
	Line int

	SpanContext trace.SpanContext

	Fields []Field
}

Entry represents the structure of a log entry. It is the argument to the sink when logging.

type Field

type Field interface {
	LogKey() string
	Value
}

Field represents a log field.

func Error

func Error(err error) Field

Error is the standard key used for logging a Go error value.

func F

func F(name string, v interface{}) Field

F is used to log arbitrary fields with the logger.

func Map added in v0.1.0

func Map(fs ...Field) []Field

Map is used to create an ordered map of fields that can be logged.

type Level added in v0.1.0

type Level int

Level represents a log level.

const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelCritical
	LevelFatal
)

The supported log levels.

func (Level) String added in v0.1.0

func (l Level) String() string

type Logger

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

Logger allows logging a ordered slice of fields to an underlying set of sinks.

func Make

func Make(s Sink) Logger

Make creates a logger that writes logs to sink.

func Tee

func Tee(ls ...Logger) Logger

Tee enables logging to multiple loggers.

func (Logger) Critical

func (l Logger) Critical(ctx context.Context, msg string, fields ...Field)

Critical logs the msg and fields at LevelCritical.

func (Logger) Debug

func (l Logger) Debug(ctx context.Context, msg string, fields ...Field)

Debug logs the msg and fields at LevelDebug.

func (Logger) Error

func (l Logger) Error(ctx context.Context, msg string, fields ...Field)

Error logs the msg and fields at LevelError.

func (Logger) Fatal

func (l Logger) Fatal(ctx context.Context, msg string, fields ...Field)

Fatal logs the msg and fields at LevelFatal.

func (Logger) Helper added in v0.2.0

func (l Logger) Helper()

Helper marks the calling function as a helper and skips it for source location information.

func (Logger) Info

func (l Logger) Info(ctx context.Context, msg string, fields ...Field)

Info logs the msg and fields at LevelInfo.

func (Logger) Named added in v0.2.0

func (l Logger) Named(name string) Logger

Named names the logger. If there is already a name set, it will be joined by ".". E.g. if the name is currently "my_component" and then later the name "my_pkg" is set, then the final component will be "my_component.my_pkg".

func (Logger) SetLevel added in v0.1.0

func (l Logger) SetLevel(level Level)

SetLevel changes the Logger's level.

func (Logger) Sync added in v0.2.0

func (l Logger) Sync()

Sync calls Sync on the sinks underlying the logger. Used it to ensure all logs are flushed during exit.

func (Logger) Warn

func (l Logger) Warn(ctx context.Context, msg string, fields ...Field)

Warn logs the msg and fields at LevelWarn.

func (Logger) With

func (l Logger) With(fields ...Field) Logger

With returns a Logger that prepends the given fields on every logged entry. It will append to any fields already in the Logger.

type Sink added in v0.1.0

type Sink interface {
	LogEntry(ctx context.Context, e Entry) error
	Sync() error
}

Sink is the destination of a Logger.

type Value

type Value interface {
	LogValue() interface{}
}

Value represents a log value. The value returned will be logged. Your own types can implement this interface to override their logging appearance.

type ValueFunc added in v0.1.0

type ValueFunc func() interface{}

ValueFunc is a convenient function wrapper around Value.

func (ValueFunc) LogValue added in v0.1.0

func (v ValueFunc) LogValue() interface{}

LogValue implements Value.

Directories

Path Synopsis
internal
assert
Package assert is a helper package for asserting equality and generating diffs in tests.
Package assert is a helper package for asserting equality and generating diffs in tests.
humanfmt
Package humanfmt contains the code to format slog.Entry into a human readable format.
Package humanfmt contains the code to format slog.Entry into a human readable format.
syncwriter
Package syncwriter implements a concurrency safe io.Writer wrapper.
Package syncwriter implements a concurrency safe io.Writer wrapper.
sloggers
sloghuman
Package sloghuman contains the slogger that writes logs in a human readable format.
Package sloghuman contains the slogger that writes logs in a human readable format.
slogjson
Package slogjson contains the slogger that writes logs in a JSON format.
Package slogjson contains the slogger that writes logs in a JSON format.
slogstackdriver
Package slogstackdriver contains the slogger for GCP.
Package slogstackdriver contains the slogger for GCP.
slogtest
Package slogtest contains the slogger for use with Go's testing package.
Package slogtest contains the slogger for use with Go's testing package.
Package slogval is used by the default sloggers to take a []slog.Field and convert it into a easily marshable slogval.Value.
Package slogval is used by the default sloggers to take a []slog.Field and convert it into a easily marshable slogval.Value.

Jump to

Keyboard shortcuts

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