Coder Social home page Coder Social logo

slog's Introduction

slog, a back-end agnostic interface for structured logs

Go Reference Codebeat Badge

slog.Logger provides a simple standardised interface for structured logs for libraries. It supports six log levels and fields with unique string labels (keys).

Interface

Every method of this interface, with the exception of Print(), returns a slog.Logger so it can be daisy chained when composing a log entry. A log entry begins with setting the level followed by optional addition of fields and a call stack and ends with a message calling a Print method. Based on the specified level an entry can be enabled or disabled. Calls to methods on disabled entries will cause no action unless it's used to create a new entry with a level that is enabled.

Log Levels

An slog.Logger entry can have of one of six levels, of which Fatal is expected to end the execution just like the standard log.Fatal()right after adding the log entry, and Panic to raise a recoverable panic like log.Panic().

  1. Debug
  2. Info
  3. Warn
  4. Error
  5. Fatal
  6. Panic

New log entries can be created by calling the named shortcut methods (Debug(), Info(), Warn(), Error(), Fatal(), and Panic()) or via WithLevel(level).

Enabled

A log entry is considered Enabled if the handler would actually log entries of the specified level. It is always safe to operate on disabled loggers and the cost of should be negletable as when a logger is not Enabled() string formatting operations or fields and stack commands are not performed.

Sometimes it is useful to know if a certain level is Enabled so you can decide between two levels with different degree of detail. For this purpose one can use WithEnabled() like this:

if log, ok := logger.Debug().WithEnabled(); ok {
	log.WithField("request", req).Print("Let's write detailed debug stuff")
} else if log, ok := logger.Info().WithEnabled(); ok {
	log.Print("Let's write info stuff instead")
}

Logs of Fatal and Panic level are expected to exit/panic regardless of the Enabled state.

Fields

In slog fields are unique key/value pairs where the key is a non-empty string and the value could be any type.

Call Stack

A Call stack is attached to a log entry considering the given distance to a caller/initiator function.

Print

slog.Logger support three Print methods mimicking their equivalent in the fmt package from the standard library. Print(), Println(), and Printf() that finally attempt to emit the log entry with the given message and any previously attached Field.

Standard *log.Logger

In order to be compatible with the standard library's provided log.Logger, slog provides an io.Writer interface connected to a handler function that is expected to parse the entry and call a provided slog.Logger as appropriate. This writer is created by calling NewLogWriter and passing the logger and the handler function, which is then passed to log.New() to create the *log.Logger.

Alternatively a generic handler is provided when using NewStdLogger().

Handlers

A handler is an object that implements the slog.Logger interface. We provide handlers to use popular loggers as backend.

We also offer backend independent handlers

  • cblog, a implementation that allows you to receive log entries through a channel.
  • filter, that can filter by level and also alter log entries before passing them to another slog.Logger.
  • discard, a placeholder that won't log anything but saves the user from checking if a logger was provided or not every time.

slog's People

Contributors

amery avatar karasz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

zhanglei

slog's Issues

zerolog: Fatal() and Panic() continue

The following, using zlog.Fatal() or zlog.Panic() ends before the unreachable mark

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	zlog := zerolog.New(zerolog.ConsoleWriter{
		Out: os.Stderr,
	})
	zlog.Fatal().Msg("Fatal")
	panic("unreachable")
}
�[90m<nil>�[0m �[1m�[31mFTL�[0m�[0m Fatal

Program exited.

but when using our wrapper, it doesn't.

package main

import (
	"os"

	slog "github.com/darvaza-proxy/slog/handlers/zerolog"
	"github.com/rs/zerolog"
)

func main() {
	zlog := zerolog.New(zerolog.ConsoleWriter{
		Out: os.Stderr,
	})
	log := slog.New(&zlog)
	log.Fatal().Print("Fatal")
	panic("unreachable")
}
�[90m<nil>�[0m �[1m�[31mFTL�[0m�[0m Fatal
panic: unreachable

goroutine 1 [running]:
main.main()
	/tmp/sandbox1363277814/prog.go:18 +0x15b

Program exited.

Log back-end location

I was thinking if we should not have a backends folder for the log backends. Having them all in root seems a bit messy.
Something like

mkdir -p backends
git mv zerolog backends/zerolog

It will make #12 a bit easier to implement.

tests

$ make test
▶ generating subproject rules
▶ test: root
?       github.com/darvaza-proxy/slog   [no test files]
?       github.com/darvaza-proxy/slog/internal  [no test files]
▶ test: logrus
?       github.com/darvaza-proxy/slog/logrus    [no test files]
▶ test: zap
?       github.com/darvaza-proxy/slog/zap       [no test files]
▶ test: zerolog
?       github.com/darvaza-proxy/slog/zerolog   [no test files]
▶ test: cblog
?       github.com/darvaza-proxy/slog/cblog     [no test files]

we need to find a way to test implementation and compliance of each adaptor we implement. currently reduced to zerolog and cblog, but also the *log.Logger writer at the top level and the internal/ helpers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.