logger

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2024 License: Apache-2.0 Imports: 10 Imported by: 46

README

logger

Common logger library for golang projects

import "github.com/relex/gotils/logger"

logger.Info("hey there!")
logger.Fatal("Oh my god!")
...
logger.WithField("file", "log.txt").Errorf("failed to open: %v", err)
...
subLogger := logger.WithFields(map[string]interface{}{
	"key2": "val2",
	"key3": "val3",
})
subLogger.Warn("something broke")
...
logger.Exit(0) // must exit the program via .Exit to flush logs properly

Log levels:

  • Trace
  • Debug
  • Info
  • Warn
  • Error
  • Fatal
  • Panic

The default level is Info. To change:

export LOG_LEVEL="debug"   # case-insensitive

or

logger.SetLogLevel(logger.DebugLevel)

PS: trace-level logs are never forwarded to upstream regardless of the log level set.

Fatal and Panic

  • logger.Fatal ends the program with exit code 1 after logging. It uses logger.Exit and waits at least 3 seconds for log forwarding connection to flush if set up by SetUpstreamEndpoint.
  • logger.Panic calls panic after logging. It only waits 1 second for log forwarding connection to flush.

Log format

By default logger is using the TextFormat, which is like:

time="2006/02/01T15:04:05.123+0200" level=debug msg="Started observing beach"

But you can select a JSON format with SetFormat function.

logger.SetJSONFormat()

Then, the log, will be like:

{"timestamp":"2006/02/01T15:04:05.123+0200","level":"info","message":"A group of walrus emerges from the ocean"}

Log output

By default all logs are going to stderr, but you can set it to go into file:

err := logger.SetOutputFile("/tmp/my_app.log")
if err != nil {
    // handle
}

Log forwarding

Forwarding to upstream for log collection can be enabled by:

logger.SetUpstreamEndpoint("127.0.0.1:10501")

The upstream address needs to be an address to Datadog agent's TCP input.

Only TCP protocol is supported and the format of logs to upstream is always JSON, regardless of the main format used by logger(s).

Error recovery

There are two implementations for log forwarding to upstream: buffered for remote endpoint and unbuffered for local endpoint. It's chosen automatically by the type of endpoint host.

The buffered implementation queues all logs in GO channel and flush it every 1/10 second; It deals with network errors and attempts reconnection or resending indefinitely until logger.Exit is called (when it would retry one more time to flush all remaining logs).

The unbuffered one ignores any logs failed to send, as error recovery would block logging functions for too long. However, it attempts to reconnect for every new log if the previous one fails.

Both print internal errors to stderr.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AtExit

func AtExit(handler func())

AtExit registers a function to be called when the program is shut down.

AtExit can be called multiple times and functions registered are called in reverse order (like "defer").

Since go doesn't provide any shutdown callback at the moment, the mechanism only works when application quits by calling Exit() here.

func Debug

func Debug(args ...interface{})

Debug logs debugging information

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs debugging information with formatting

func Error

func Error(args ...interface{})

Error logs errors via the root logger

func Errorf

func Errorf(format string, args ...interface{})

Errorf logs errors with formatting

func Exit

func Exit(code int)

Exit quits the program by calling exit on the underlying logger and flushes all remaining logs if any

func Fatal

func Fatal(args ...interface{})

Fatal logs critical errros

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf logs critical errros with formatting

func Info

func Info(args ...interface{})

Info logs information

func Infof

func Infof(format string, args ...interface{})

Infof logs information with formatting

func Panic

func Panic(args ...interface{})

Panic logs critical errors and exits the program

func Panicf

func Panicf(format string, args ...interface{})

Panicf logs critical errors with formatting and exits the program

func SetAutoFormat

func SetAutoFormat()

SetAutoFormat uses the environment variable `LOG_COLOR` and terminal detection to select console or text output format

SetAutoFormat is the default choice and always invoked during initialization

func SetAutoJSONFormat

func SetAutoJSONFormat()

SetAutoJSONFormat uses the environment variable `LOG_COLOR` and terminal detection to select console or JSON output format

func SetDefaultLevel

func SetDefaultLevel()

SetDefaultLevel sets the default logging level depending on environment variable "LOG_LEVEL"

func SetJSONFormat

func SetJSONFormat()

SetJSONFormat sets the upstream compatible logging format in JSON. For example:

{"timestamp":"2006/02/01T15:04:05.123+0200","level":"info","message":"A group of walrus emerges from theocean"}

func SetLogLevel

func SetLogLevel(level LogLevel)

SetLogLevel sets the level of the root logger

func SetOutput

func SetOutput(output io.Writer)

SetOutput configures the root logger to output into specified Writer

func SetOutputFile

func SetOutputFile(path string) error

SetOutputFile configure the root logger to write into specified file

func SetTextFormat

func SetTextFormat()

SetTextFormat sets the default text format. For example:

time="2006/02/01T15:04:05.123+0200" level=debug msg="Started observing beach"

func SetUpstreamEndpoint

func SetUpstreamEndpoint(endpoint string)

SetUpstreamEndpoint configures the root logger to duplicate and forward all logs to upstream This function should be called at most once.

func Trace

func Trace(args ...interface{})

Trace logs tracing information

func Tracef

func Tracef(format string, args ...interface{})

Tracef logs tracing information with formatting

func Warn

func Warn(args ...interface{})

Warn logs warnings

func Warnf

func Warnf(format string, args ...interface{})

Warnf logs warnings with formatting

Types

type Fields

type Fields map[string]interface{}

Fields type, used to pass to `WithFields`

type LogLevel

type LogLevel string

LogLevel represents the logging level. The level here is abstract and meant to be translated to real logging levels used by the underlying library.

const (
	PanicLevel LogLevel = "panic"
	FatalLevel LogLevel = "fatal"
	ErrorLevel LogLevel = "error"
	WarnLevel  LogLevel = "warn"
	InfoLevel  LogLevel = "info"
	DebugLevel LogLevel = "debug"
	TraceLevel LogLevel = "trace"
)

Logging levels

func GetLogLevel

func GetLogLevel() LogLevel

type Logger

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

Logger wraps a logger (Entry) of the underlying logging library Logger should always be passed by value

func Root

func Root() Logger

Root gets the root logger that can be used to create sub-loggers.

Calling global logging functions in the package is the same as calling methods in the root logger.

func WithField

func WithField(key string, value interface{}) Logger

WithField creates a sub-logger from the root logger with specifid field

func WithFields

func WithFields(fields map[string]interface{}) Logger

WithFields creates a sub-logger from the root logger with specifid fields

func (Logger) Debug

func (logger Logger) Debug(args ...interface{})

Debug logs debugging information

func (Logger) Debugf

func (logger Logger) Debugf(format string, args ...interface{})

Debugf logs debugging information with formatting

func (Logger) Eprint

func (logger Logger) Eprint(args ...interface{}) error

Eprint prints the given arguments with fields in this logger to a StructuredError

Fields in the logger are copied into StructuredError for later logging

func (Logger) Eprintf

func (logger Logger) Eprintf(format string, args ...interface{}) error

Eprintf formats the given arguments with fields in this logger to a StructuredError

Fields in the logger are copied into StructuredError for later logging

func (Logger) Error

func (logger Logger) Error(args ...interface{})

Error logs errors via the root logger

func (Logger) Errorf

func (logger Logger) Errorf(format string, args ...interface{})

Errorf logs errors with formatting

func (Logger) Ewrap

func (logger Logger) Ewrap(innerError error) error

Ewrap wraps the given error inside a newly-created StructuredError with context information

Fields in the logger are copied into StructuredError for later logging

func (Logger) Fatal

func (logger Logger) Fatal(args ...interface{})

Fatal logs critical errros

func (Logger) Fatalf

func (logger Logger) Fatalf(format string, args ...interface{})

Fatalf logs critical errros with formatting

func (Logger) Info

func (logger Logger) Info(args ...interface{})

Info logs information

func (Logger) Infof

func (logger Logger) Infof(format string, args ...interface{})

Infof logs information with formatting

func (Logger) NewWriter

func (logger Logger) NewWriter(level LogLevel) io.Writer

NewWriter creates an io.Writer on this logger. Each .Write() call would log a message.

func (Logger) Panic

func (logger Logger) Panic(args ...interface{})

Panic logs critical errors and exits the program

func (Logger) Panicf

func (logger Logger) Panicf(format string, args ...interface{})

Panicf logs critical errors with formatting and exits the program

func (Logger) Sprint

func (logger Logger) Sprint(args ...interface{}) string

Sprint prints the given arguments with fields in this logger to a string

e.g. "[MyClass] name=Foo status=200 My message"

func (Logger) Sprintf

func (logger Logger) Sprintf(format string, args ...interface{}) string

Sprintf formats the given arguments with fields in this logger to a string

e.g. "[MyClass] name=Foo status=200 Hi '<someone>'"

func (Logger) Trace

func (logger Logger) Trace(args ...interface{})

Trace logs tracing information

func (Logger) Tracef

func (logger Logger) Tracef(format string, args ...interface{})

Tracef logs tracing information with formatting

func (Logger) Warn

func (logger Logger) Warn(args ...interface{})

Warn logs warnings

func (Logger) Warnf

func (logger Logger) Warnf(format string, args ...interface{})

Warnf logs warnings with formatting

func (Logger) WithField

func (logger Logger) WithField(key string, value interface{}) Logger

WithField creates a sub-logger with specifid field

func (Logger) WithFields

func (logger Logger) WithFields(fields map[string]interface{}) Logger

WithFields creates a sub-logger with specifid fields

type StructuredError

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

StructuredError represents a thing that carries metadata that should be elevated to log fields when logged

func NewStructuredError

func NewStructuredError(srcFields map[string]interface{}, err error) *StructuredError

NewStructuredError creates a StructuredError with a map of fields (to be copied) and a message

func (*StructuredError) Error

func (se *StructuredError) Error() string

func (*StructuredError) String

func (se *StructuredError) String() string

func (*StructuredError) Unwrap

func (se *StructuredError) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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