package
1.1.1
Repository: https://github.com/relex/gotils.git
Documentation: pkg.go.dev

# 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.

# Packages

No description provided by the author

# Functions

AtExit registers a function to be called when the program is shut down.
Debug logs debugging information.
Debugf logs debugging information with formatting.
Error logs errors via the root logger.
Errorf logs errors with formatting.
Exit quits the program by calling exit on the underlying logger and flushes all remaining logs if any.
Fatal logs critical errros.
Fatalf logs critical errros with formatting.
No description provided by the author
Info logs information.
Infof logs information with formatting.
NewStructuredError creates a StructuredError with a map of fields (to be copied) and a message.
Panic logs critical errors and exits the program.
Panicf logs critical errors with formatting and exits the program.
Root gets the root logger that can be used to create sub-loggers.
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.
SetAutoJSONFormat uses the environment variable `LOG_COLOR` and terminal detection to select console or JSON output format.
SetDefaultLevel sets the default logging level depending on environment variable "LOG_LEVEL".
SetJSONFormat sets the upstream compatible logging format in JSON.
SetLogLevel sets the level of the root logger.
SetOutput configures the root logger to output into specified Writer.
SetOutputFile configure the root logger to write into specified file.
SetTextFormat sets the default text format.
SetUpstreamEndpoint configures the root logger to duplicate and forward all logs to upstream This function should be called at most once.
Trace logs tracing information.
Tracef logs tracing information with formatting.
Warn logs warnings.
Warnf logs warnings with formatting.
WithField creates a sub-logger from the root logger with specifid field.
WithFields creates a sub-logger from the root logger with specifid fields.

# Constants

Logging levels.
Logging levels.
Logging levels.
Logging levels.
Logging levels.
Logging levels.
Logging levels.

# Structs

Logger wraps a logger (Entry) of the underlying logging library Logger should always be passed by value.
StructuredError represents a thing that carries metadata that should be elevated to log fields when logged.

# Type aliases

Fields type, used to pass to `WithFields`.
LogLevel represents the logging level.