log

package module
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2020 License: MIT Imports: 7 Imported by: 32

README

ContainerSSH - Launch Containers on Demand

ContainerSSH Logging Library

Go Report Card LGTM Alerts

This library provides internal logging for ContainerSSH. Its functionality is very similar to how syslog is structured.

Note: This is a developer documentation.
The user documentation for ContainerSSH is located at containerssh.github.io.

Getting a logger

The main interface provided by this library is the Logger interface, which is described in logger.go.

You could use it like this:

type MyModule struct {
    logger log.Logger 
}

func (m * MyModule) DoSomething() {
    m.logger.Debug("This is a debug message")
}

The logger provides logging functions for the following levels:

  • Debug
  • Info
  • Notice
  • Warning
  • Error
  • Critical
  • Alert
  • Emergency

Each of these functions have the following 4 variants:

  • Debug logs a string message
  • Debuge logs an error
  • Debugd logs an arbitrary data structure (interface{})
  • Debugf performs a string formating with fmt.Sprintf before logging

In addition, the logger also provides a generic Log(...interface{}) function for compatibility that logs in the info log level.

Creating logger

The simplest way to create a logger is to use the convenience functions:

config := log.Config{
    // Log levels are: Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency
    Level: log.LevelNotice,
    // Supported formats: Text, LJSON
    Format: log.FormatText,
}
// module is an optional module descriptor for log messages. Can be empty.
module        := "someModule"
logger        := log.New(config, module, os.Stdout)
loggerFactory := log.NewFactory(os.Stdout)

You can also create a custom pipeline if you wish:

writer          := os.Stdout
minimumLogLevel := log.LevelInfo
logFormatter    := log.NewLJsonLogFormatter()
module          := "someModule"
p := pipeline.NewLoggerPipeline(minimumLogLevel, module, logFormatter, writer)
p.Warning("test") 

This will create a pipeline that writes log messages to the standard output in newline-delimited JSON format. You can, of course, also implement your own log formatter by implementing the interface in formatter.go.

Plugging in the go logger

This package also provides the facility to plug in the go logger. This can be done by creating a logger as follows:

import (
  goLog "log"
  "github.com/containerssh/log"
)

goLogWriter := log.NewGoLogWriter(logger)
goLogger := goLog.New(goLogWriter, "", 0)
goLogger.Println("Hello world!")

If you want to change the log facility globally:

import (
  goLog "log"
  "github.com/containerssh/log"
)

goLogWriter := log.NewGoLogWriter(logger)
goLog.SetOutput(goLogWriter)
goLog.Println("Hello world!")

Log formats

We currently support two log formats: text and ljson

The text format

The text format is structured as follows:

TIMESTAMP[TAB]LEVEL[TAB]MODULE[TAB]MESSAGE[NEWLINE]
  • TIMESTAMP is the timestamp of the message in RFC3339 format.
  • LEVEL is the level of the message (debug, info, notice, warning, error, critical, alert, emergency)
  • MODULE is the name of the module logged. May be empty.
  • MESSAGE is the text message or structured data logged.

This format is recommended for human consumption only.

The ljson format

This format logs in a newline-delimited JSON format. Each message has the following format:

{"timestamp": "TIMESTAMP", "level": "LEVEL", "module": "MODULE", "message": "MESSAGE", "details": "DETAILS"}
  • TIMESTAMP is the timestamp of the message in RFC3339 format.
  • LEVEL is the level of the message (debug, info, notice, warning, error, critical, alert, emergency)
  • MODULE is the name of the module logged. May be absent if not sent.
  • MESSAGE is the text message. May be absent if not set.
  • DETAILS is a structured log message. May be absent if not set.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewGoLogWriter added in v0.9.1

func NewGoLogWriter(backendLogger Logger) io.Writer

NewGoLogWriter creates an adapter for the go logger that writes using the Log method of the logger.

Types

type Config added in v0.9.3

type Config struct {
	// Level describes the minimum level to log at
	Level Level `json:"level" yaml:"level" default:"notice"`
	// Format describes the log message format
	Format Format `json:"format" yaml:"format" default:"ljson"`
}

Config describes the logging settings.

type Format added in v0.9.3

type Format string

Format is the logging format to use.

const (
	// FormatLJSON is a newline-delimited JSON log format.
	FormatLJSON Format = "ljson"
	// FormatText prints the logs as plain text.
	FormatText Format = "text"
)

func (Format) Validate added in v0.9.3

func (format Format) Validate() error

Validate returns an error if the format is invalid.

type Formatter added in v0.9.3

type Formatter interface {
	// Format a string message. The module may be empty.
	Format(level Level, module string, message string) []byte
	// Format a data object. The module may be empty.
	FormatData(level Level, module string, data interface{}) []byte
}

Formatter an interface that can format a log message or a data interface into a data stream.

func NewLJsonLogFormatter added in v0.9.3

func NewLJsonLogFormatter() Formatter

NewLJsonLogFormatter Factory for the newline-delimited JSON formatter.

func NewTextLogFormatter added in v0.9.3

func NewTextLogFormatter() Formatter

NewTextLogFormatter Factory for the text format.

type Level

type Level int8

Level syslog-style log level identifiers

const (
	LevelDebug     Level = 7
	LevelInfo      Level = 6
	LevelNotice    Level = 5
	LevelWarning   Level = 4
	LevelError     Level = 3
	LevelCritical  Level = 2
	LevelAlert     Level = 1
	LevelEmergency Level = 0
)

Supported values for Level

func (Level) String

func (level Level) String() (LevelString, error)

String Convert the int level to the string representation

func (Level) Validate

func (level Level) Validate() error

Validate if the log level has a valid value

type LevelString

type LevelString string

LevelString is a type for supported log level strings

const (
	LevelDebugString     LevelString = "debug"
	LevelInfoString      LevelString = "info"
	LevelNoticeString    LevelString = "notice"
	LevelWarningString   LevelString = "warning"
	LevelErrorString     LevelString = "error"
	LevelCriticalString  LevelString = "crit"
	LevelAlertString     LevelString = "alert"
	LevelEmergencyString LevelString = "emerg"
)

List of valid string values for log levels

func (LevelString) ToLevel

func (level LevelString) ToLevel() (Level, error)

ToLevel convert the string level to the int representation

type Logger

type Logger interface {
	// SetLevel sets the logging level of the current logger.
	SetLevel(level Level)
	Debug(message string)
	Debuge(err error)
	Debugd(data interface{})
	Debugf(format string, args ...interface{})
	Info(message string)
	Infoe(err error)
	Infod(data interface{})
	Infof(format string, args ...interface{})
	Notice(message string)
	Noticee(err error)
	Noticed(data interface{})
	Noticef(format string, args ...interface{})
	Warning(message string)
	Warninge(err error)
	Warningd(data interface{})
	Warningf(format string, args ...interface{})
	Error(message string)
	Errore(err error)
	Errord(data interface{})
	Errorf(format string, args ...interface{})
	Critical(message string)
	Criticale(err error)
	Criticald(data interface{})
	Criticalf(format string, args ...interface{})
	Alert(message string)
	Alerte(err error)
	Alertd(data interface{})
	Alertf(format string, args ...interface{})
	Emergency(message string)
	Emergencye(err error)
	Emergencyd(data interface{})
	Emergencyf(format string, args ...interface{})
	Log(...interface{})
}

Logger The logger interface provides logging facilities on various levesl

func New added in v0.9.3

func New(config Config, module string, writer io.Writer) (Logger, error)

New creates a standard logger pipeline.

- config is the configuration structure for the logger - module is a descriptor for the module that's logging. Can be empty. - writer is the target writer the logs should be sent to.

goland:noinspection GoUnusedExportedFunction

func NewLoggerPipeline added in v0.9.3

func NewLoggerPipeline(
	level Level,
	module string,
	formatter Formatter,
	writer io.Writer,
) Logger

NewLoggerPipeline creates a new logger pipeline with the configured minimum log level, a formatter to transform, and a writer to write the log to.

type LoggerFactory

type LoggerFactory interface {
	// Make creates a new logger with the specified configuration and module.
	//
	// - config is the configuration structure.
	// - module is the module that's logging. Can be empty.
	//
	// Return:
	//
	// - Logger is the logger created.
	// - error is returned if the configuration was invalid.
	Make(config Config, module string) (Logger, error)
}

LoggerFactory is a factory to create a logger on demand

func NewFactory added in v0.9.3

func NewFactory(writer io.Writer) LoggerFactory

NewFactory creates a standard logger pipeline factory.

- writer is the target writer.

goland:noinspection GoUnusedExportedFunction

func NewLoggerPipelineFactory added in v0.9.3

func NewLoggerPipelineFactory(writer io.Writer) LoggerFactory

NewLoggerPipelineFactory create a pipeline logger factory

Jump to

Keyboard shortcuts

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