log

package module
v2.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2021 License: MIT Imports: 17 Imported by: 9

README

go-log

DAOT Labs' fork of ipfs/go-log.

Go Reference

go-log wraps zap to provide a logging facade. go-log manages logging instances and allows for their levels to be controlled individually.

Additional features of this fork

Added formats
  • CompactOutput: a compact format which looks like:
D[2021-05-13T17:49:52.413+0800]	example/log.go:52	for Debug
I[2021-05-13T17:49:52.413+0800]	example/log.go:52	for Info
W[2021-05-13T17:49:52.413+0800]	example/log.go:52	for Warn
E[2021-05-13T17:49:52.413+0800]	example/log.go:52	for Error
p[2021-05-13T17:49:52.413+0800]	example/log.go:52	for DPanic
P[2021-05-13T17:49:52.413+0800]	example/log.go:52	for Panic
F[2021-05-13T17:49:52.413+0800]	example/log.go:52	for Fatal
  • ColorizedCompactOutput: same as CompactOutput but colorized
Added config options
  • AutoColor: automatically switches between formats and their colorized counterparts (ColorizedOutput <-> PlaintextOutput, ColorizedCompactOutput <-> CompactOutput), if the current program is run from a terminal it switches to the colorized version, vice versa
  • AutoStdout: automatically enables stdout output if the current program is run from a terminal, or ((File is not set or not correct) and (URL is not set))
  • Sampling: configs log sampling
  • Lumberjack: configs log rolling using Lumberjack

Install

go get github.com/daotl/go-log/v2

Usage

Once the package is imported under the name logging, an instance of EventLogger can be created like so:

var log = logging.Logger("subsystem name")

It can then be used to emit log messages in plain printf-style messages at seven standard levels:

Levels may be set for all loggers:

lvl, err := logging.LevelFromString("error")
if err != nil {
	panic(err)
}
logging.SetAllLoggers(lvl)

or individually:

err := logging.SetLogLevel("net:pubsub", "info")
if err != nil {
	panic(err)
}

or by regular expression:

err := logging.SetLogLevelRegex("net:.*", "info")
if err != nil {
	panic(err)
}
Environment Variables

This package can be configured through various environment variables.

GOLOG_LOG_LEVEL

Specifies the log-level, both globally and on a per-subsystem basis.

For example, the following will set the global minimum log level to error, but reduce the minimum log level for subsystem1 to info and reduce the minimum log level for subsystem2 to debug.

export GOLOG_LOG_LEVEL="error,subsystem1=info,subsystem2=debug"
GOLOG_FILE

Specifies that logs should be written to the specified file. If this option is not specified, logs are written to standard error.

export GOLOG_FILE="/path/to/my/file.log"
GOLOG_OUTPUT

Specifies where logging output should be written. Can take one or more of the following values, combined with +:

  • stdout -- write logs to standard out.
  • stderr -- write logs to standard error.
  • file -- write logs to the file specified by GOLOG_FILE

For example, if you want to log to both a file and standard error:

export GOLOG_FILE="/path/to/my/file.log"
export GOLOG_OUTPUT="stderr+file"

Setting only GOLOG_FILE will prevent logs from being written to standard error.

GOLOG_LOG_FMT

Specifies the log message format. It supports the following values:

  • color -- human readable, colorized (ANSI) output.
  • nocolor -- human readable, plain-text output.
  • json -- structured JSON.
  • compactcolor -- human readable, compact colorized (ANSI) output.
  • compactnocolor -- human readable, compact output.

For example, to log structured JSON (for easier parsing):

export GOLOG_LOG_FMT="json"

The logging format defaults to color when the output is a terminal, and nocolor otherwise.

GOLOG_AUTO_COLOR

See AutoColor in Added config options.

GOLOG_LOG_LABELS

Specifies a set of labels that should be added to all log messages as comma-separated key-value pairs. For example, the following add {"app": "example_app", "dc": "sjc-1"} to every log entry.

export GOLOG_LOG_LABELS="app=example_app,dc=sjc-1"

Contribute

Feel free to join in. All welcome. Open an issue!

License

MIT

Documentation

Overview

Package log is the logging library used by IPFS & libp2p (https://github.com/ipfs/go-ipfs).

Index

Constants

This section is empty.

Variables

View Source
var (
	LevelDebug  = LogLevel(zapcore.DebugLevel)
	LevelInfo   = LogLevel(zapcore.InfoLevel)
	LevelWarn   = LogLevel(zapcore.WarnLevel)
	LevelError  = LogLevel(zapcore.ErrorLevel)
	LevelDPanic = LogLevel(zapcore.DPanicLevel)
	LevelPanic  = LogLevel(zapcore.PanicLevel)
	LevelFatal  = LogLevel(zapcore.FatalLevel)
)
View Source
var ErrNoSuchLogger = errors.New("error: No such logger")

ErrNoSuchLogger is returned when the util pkg is asked for a non existant logger

Functions

func FormatRFC3339

func FormatRFC3339(t time.Time) string

FormatRFC3339 returns the given time in UTC with RFC3999Nano format.

func GetSubsystems

func GetSubsystems() []string

GetSubsystems returns a slice containing the names of the current loggers

func NopLogger added in v2.3.1

func NopLogger() *zap.SugaredLogger

NopLogger returns a no-op Logger. It never writes out logs or internal errors.

func SetAllLoggers

func SetAllLoggers(lvl LogLevel)

SetAllLoggers changes the logging level of all loggers to lvl

func SetDebugLogging

func SetDebugLogging()

SetDebugLogging calls SetAllLoggers with logging.DEBUG

func SetLogLevel

func SetLogLevel(name, level string) error

SetLogLevel changes the log level of a specific subsystem name=="*" changes all subsystems

func SetLogLevelRegex

func SetLogLevelRegex(e, l string) error

SetLogLevelRegex sets all loggers to level `l` that match expression `e`. An error is returned if `e` fails to compile.

func SetPrimaryCore added in v2.3.0

func SetPrimaryCore(core zapcore.Core)

SetPrimaryCore changes the primary logging core. If the SetupLogging was called then the previously configured core will be replaced.

func SetupLogging

func SetupLogging(cfg Config)

SetupLogging will initialize the logger backend and set the flags. TODO calling this in `init` pushes all configuration to env variables - move it out of `init`? then we need to change all the code (js-ipfs, go-ipfs) to call this explicitly - have it look for a config file? need to define what that is

func TestingLogger added in v2.3.1

func TestingLogger() *zap.SugaredLogger

TestingLogger returns a Logger which writes to STDOUT if test(s) are being run with the verbose (-v) flag, NopLogger otherwise.

NOTE: - A call to NewTestingLogger() must be made inside a test (not in the init func) because verbose flag only set at the time of testing.

Types

type Config

type Config struct {
	// Format overrides the format of the log output. Defaults to ColorizedOutput
	Format LogFormat

	// AutoColor automatically switches between formats and their colorized counterparts
	// (ColorizedOutput <-> PlaintextOutput, ColorizedCompactOutput <-> CompactOutput),
	// if the current program is run from a terminal it switches to the colorized version, vice versa.
	AutoColor bool

	// Level is the default minimum enabled logging level.
	Level LogLevel

	// SubsystemLevels are the default levels per-subsystem. When unspecified, defaults to Level.
	SubsystemLevels map[string]LogLevel

	// Sampling configs log sampling, disabled if nil.
	Sampling *zap.SamplingConfig

	// Stdout indicates whether logs should be written to stdout.
	Stdout bool

	// Stderr indicates whether logs should be written to stderr.
	Stderr bool

	// File is a path to a file that logs will be written to.
	File string

	// Lumberjack configs log rolling using Lumberjack, disabled if nil.
	// Lumberjack.Filename will be ignored and set to File.
	Lumberjack *lumberjack.Logger

	// URL with schema supported by zap. Use zap.RegisterSink
	URL string

	// AutoStdout automatically enables stdout output if the current program is
	// run from a terminal, or ((File is not set or not correct) and (URL is not set)).
	AutoStdout bool

	// Labels is a set of key-values to apply to all loggers
	Labels map[string]string
}

type EventLogger

type EventLogger interface {
	StandardLogger
}

EventLogger extends the StandardLogger interface to allow for log items containing structured metadata

type LogFormat

type LogFormat int
const (
	ColorizedOutput LogFormat = iota
	PlaintextOutput
	JSONOutput
	ColorizedCompactOutput
	CompactOutput
)

type LogLevel

type LogLevel zapcore.Level

LogLevel represents a log severity level. Use the package variables as an enum.

func LevelFromString

func LevelFromString(level string) (LogLevel, error)

LevelFromString parses a string-based level and returns the corresponding LogLevel.

Supported strings are: DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL, and their lower-case forms.

The returned LogLevel must be discarded if error is not nil.

type PipeReader

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

A PipeReader is a reader that reads from the logger. It is synchronous so blocking on read will affect logging performance.

func NewPipeReader

func NewPipeReader(opts ...PipeReaderOption) *PipeReader

NewPipeReader creates a new in-memory reader that reads from all loggers The caller must call Close on the returned reader when done.

By default, it:

  1. Logs JSON. This can be changed by passing the PipeFormat option.
  2. Logs everything that would otherwise be logged to the "primary" log output. That is, everything enabled by SetLogLevel. The minimum log level can be increased by passing the PipeLevel option.

func (*PipeReader) Close

func (p *PipeReader) Close() error

Close unregisters the reader from the logger.

func (*PipeReader) Read

func (p *PipeReader) Read(data []byte) (int, error)

Read implements the standard Read interface

type PipeReaderOption

type PipeReaderOption interface {
	// contains filtered or unexported methods
}

func PipeFormat

func PipeFormat(format LogFormat) PipeReaderOption

PipeFormat sets the output format of the pipe reader

func PipeLevel

func PipeLevel(level LogLevel) PipeReaderOption

PipeLevel sets the log level of logs sent to the pipe reader.

type StandardLogger

type StandardLogger interface {
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Panic(args ...interface{})
	Panicf(format string, args ...interface{})
	Warn(args ...interface{})
	Warnf(format string, args ...interface{})
}

StandardLogger provides API compatibility with standard printf loggers eg. go-logging

type ZapEventLogger

type ZapEventLogger struct {
	zap.SugaredLogger
	// contains filtered or unexported fields
}

ZapEventLogger implements the EventLogger and wraps a go-logging Logger

func Logger

func Logger(system string) *ZapEventLogger

Logger retrieves an event logger by name

func WithStacktrace added in v2.3.0

func WithStacktrace(l *ZapEventLogger, level LogLevel) *ZapEventLogger

func (*ZapEventLogger) Warning

func (logger *ZapEventLogger) Warning(args ...interface{})

Warning is for compatibility Deprecated: use Warn(args ...interface{}) instead

func (*ZapEventLogger) Warningf

func (logger *ZapEventLogger) Warningf(format string, args ...interface{})

Warningf is for compatibility Deprecated: use Warnf(format string, args ...interface{}) instead

Directories

Path Synopsis
Modified from: https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/zapcore/console_encoder.go
Modified from: https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/zapcore/console_encoder.go
zap_private
_internal/bufferpool
https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/internal/bufferpool/bufferpool.go Package bufferpool houses zap's shared internal buffer pool.
https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/internal/bufferpool/bufferpool.go Package bufferpool houses zap's shared internal buffer pool.
_internal/color
https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/internal/color/color.go Package color adds coloring functionality for TTY output.
https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/internal/color/color.go Package color adds coloring functionality for TTY output.
zapcore
https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/zapcore/json_encoder.go https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/zapcore/level_strings.go
https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/zapcore/json_encoder.go https://github.com/uber-go/zap/blob/7b21229fb3f063275f4f169f8a79ad30aa001c51/zapcore/level_strings.go

Jump to

Keyboard shortcuts

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