log

package
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2023 License: MIT Imports: 9 Imported by: 4

Documentation

Overview

Package log provides a simple and extensible logger.

## Usage

First, you need to build your logger instance, using log.NewDefaultLogger, specifying what's your output (log.EntryWriter). This default logger will provide timestamp, stacktrace and tracing for all your logs. Use log.NewLogger if you need other options. (see EntryOption)

You can then use this logger instance in 3 different ways:

  • pass your logger instance across all the functions that need it

  • push it in a context, and retrieve it in the functions that need it (see With Context)

  • set it globally, and use the global instance when needed

    // Setup your log output var logOutput log.EntryWriter var ctx context.Context

    // use instance logger := log.NewDefaultLogger(logOutput) logger.Log("my log")

    // use global log.SetGlobalLogger(logger) log.Log("my log")

    // use with context ctx = log.WithContext(ctx, logger) log.LogC(ctx, "my log")

## With Context

If you can, you should rather use logging function with context. The global functions with context will first try to get the logger from the context, but if none is found, it will use the global logger.

## Package design

Its flow is based around the Entry struct. You can log anything, (ie with log.LogAny) the input will be converted into an Entry. A set of interfaces is available so the data you are logging can implement some of them to improve readability.

The second part is the EntryWriter interface. It corresponds to the output of the logger.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alert

func Alert(msg string, options ...EntryOption)

Alert logs an alert message with additional EntryOptions.

func AlertC

func AlertC(ctx context.Context, msg string, options ...EntryOption)

AlertC logs an alert message with additional EntryOptions using FromContextOrGlobal.

func Critical

func Critical(msg string, options ...EntryOption)

Critical logs a critical message with additional EntryOptions.

func CriticalC

func CriticalC(ctx context.Context, msg string, options ...EntryOption)

CriticalC logs a critical message with additional EntryOptions using FromContextOrGlobal.

func CtxWithContext

func CtxWithContext(ctx context.Context) context.Context

CtxWithContext set the context for the logger inside the context.

func CtxWithFields

func CtxWithFields(ctx context.Context, fields map[string]interface{}) context.Context

CtxWithFields adds fields for the logger inside the context.

func CtxWithLabels

func CtxWithLabels(ctx context.Context, labels map[string]string) context.Context

CtxWithLabels adds labels for the logger inside the context.

func CtxWithOptions

func CtxWithOptions(ctx context.Context, options ...EntryOption) context.Context

CtxWithOptions adds options to the logger in the context.

func CtxWithSeverity

func CtxWithSeverity(ctx context.Context, severity Severity) context.Context

CtxWithSeverity set the default severity for the logger inside the context.

func Debug

func Debug(msg string, options ...EntryOption)

Debug logs a debug message with additional EntryOptions.

func DebugC

func DebugC(ctx context.Context, msg string, options ...EntryOption)

DebugC logs a debug message with additional EntryOptions using FromContextOrGlobal.

func Emergency

func Emergency(msg string, options ...EntryOption)

Emergency logs an emergency message with additional EntryOptions.

func EmergencyC

func EmergencyC(ctx context.Context, msg string, options ...EntryOption)

EmergencyC logs an emergency message with additional EntryOptions using FromContextOrGlobal.

func Error

func Error(msg string, options ...EntryOption)

Error logs an error message with additional EntryOptions.

func ErrorC

func ErrorC(ctx context.Context, msg string, options ...EntryOption)

ErrorC logs an error message with additional EntryOptions using FromContextOrGlobal.

func Info

func Info(msg string, options ...EntryOption)

Info logs an info message with additional EntryOptions.

func InfoC

func InfoC(ctx context.Context, msg string, options ...EntryOption)

InfoC logs an info message with additional EntryOptions using FromContextOrGlobal.

func Log

func Log(msg string, options ...EntryOption)

Log log a message using the global logger.

func LogAny

func LogAny(v interface{}, options ...EntryOption)

LogAny logs interface{}thing using the global logger.

func LogAnyC

func LogAnyC(ctx context.Context, v interface{}, options ...EntryOption)

LogAnyC logs anything using FromContextOrGlobal.

func LogC

func LogC(ctx context.Context, msg string, options ...EntryOption)

LogC log a message using FromContextOrGlobal.

func NewContext

func NewContext(ctx context.Context, l *Logger) context.Context

NewContext returns a new Context that carries value Logger.

func SetGlobalLogger

func SetGlobalLogger(l *Logger)

SetGlobalLogger sets the global logger.

func Warn

func Warn(msg string, options ...EntryOption)

Warn logs a warning message with additional EntryOptions.

func WarnC

func WarnC(ctx context.Context, msg string, options ...EntryOption)

WarnC logs a warning message with additional EntryOptions using FromContextOrGlobal.

Types

type EmptyStackTrace

type EmptyStackTrace struct{}

EmptyStackTrace is an empty stacktrace.

func (EmptyStackTrace) Frames

func (e EmptyStackTrace) Frames() []runtime.Frame

Frames implements StackTrace interface.

func (EmptyStackTrace) Last

func (e EmptyStackTrace) Last() (runtime.Frame, bool)

Last implements StackTrace interface.

func (EmptyStackTrace) String

func (e EmptyStackTrace) String() string

String implements StackTrace interface.

type Entry

type Entry struct {
	// Context is current context. Ie: the request context.
	// It is mainly used so that other EntryOption can fill other Entry fields. (ie: tracing)
	Context context.Context `json:"-"`

	// Timestamp is the time of the entry. If zero, the current time is used.
	Timestamp time.Time `json:"timestamp"`

	// Severity is the severity level of the log entry.
	Severity Severity `json:"severity"`

	// Message is the main message you want to log.
	Message string `json:"message"`

	// Labels are a map of <key:value> strings to contain data that could be indexed for faster queries.
	Labels map[string]string `json:"labels"`

	// Fields contains additional information to complete the message.
	// It can contain more complex data than labels
	Fields map[string]interface{} `json:"fields"`

	// TraceID is a unique identity of a trace.
	TraceID string `json:"trace_id"`
	// SpanID is a unique identity of a span in a trace.
	SpanID string `json:"span_id"`
	// IsTraceSampled indicates whether the trace is sampled or not.
	IsTraceSampled bool `json:"is_trace_sampled"`

	// StackTrace represents the stackTrace where the log was created.
	StackTrace StackTrace `json:"stack_trace"`
}

Entry represents a single log message. It carries all the data for your log message.

Although the fields are exported, you should use the EntryOption to modify your entries, that will avoid some weird override behavior.

func NewEntry

func NewEntry(msg string) Entry

NewEntry builds a new Entry.

type EntryMarshaler

type EntryMarshaler interface {
	Marshal(Entry) []byte
}

EntryMarshaler is able to serialize an entry to a []byte.

type EntryMarshalerFunc

type EntryMarshalerFunc func(entry Entry) []byte

The EntryMarshalerFunc type is an adapter to allow the use of ordinary functions as EntryMarshaler. If f is a function with the appropriate signature, EntryMarshalerFunc(f) is a EntryMarshaler that calls f.

func (EntryMarshalerFunc) Marshal

func (s EntryMarshalerFunc) Marshal(entry Entry) []byte

Marshal implements the EntryMarshaler interface.

type EntryOption

type EntryOption func(entry *Entry)

EntryOption is a function that will modify an entry. It can be passed to a logger to be applied to all its logging calls. EntryOptions must check that the field they modify hasn't been set to respect the option order.

func AnyOpt

func AnyOpt(v interface{}) EntryOption

AnyOpt will try to cast the given argument to extract useful data It uses single-purpose interfaces to determine its fields:

  • error, use error.Error() as message and set severity to error (if not set)
  • interface{ Context() context.Context }
  • fmt.Stringer for message.
  • interface{ Message() string }
  • interface{ Timestamp() time.Time }
  • interface{ Severity() Severity }
  • interface{ Labels() map[string]string }
  • interface{ Fields() map[string]interface{} }
  • interface { TraceID() string SpanID() string IsTraceSampled() bool }
  • interface{ StackTrace() StackTrace }

func ContextOpt

func ContextOpt(ctx context.Context) EntryOption

ContextOpt sets the context if it is still context.Background().

func FieldsOpt

func FieldsOpt(fields map[string]interface{}) EntryOption

FieldsOpt sets fields values. If a field already exists, it won't be override.

func LabelsOpt

func LabelsOpt(labels map[string]string) EntryOption

LabelsOpt sets labels values. If a label already exists, it won't be override.

func MessageOpt

func MessageOpt(message string) EntryOption

MessageOpt will set the message if it is empty.

func MultiOpt

func MultiOpt(opts ...EntryOption) EntryOption

MultiOpt combines multiple options into one EntryOption. Options order will be reversed so that the first one is executed last.

func OpencensusTraceOpt

func OpencensusTraceOpt() EntryOption

OpencensusTraceOpt sets the trace information from the opencensus context.

func OpentelemetryTraceOpt

func OpentelemetryTraceOpt() EntryOption

OpentelemetryTraceOpt sets the trace information from the opentelemetry context.

func SeverityOpt

func SeverityOpt(severity Severity) EntryOption

SeverityOpt sets the severity if it is still DefaultSeverity.

func StackTraceOpt

func StackTraceOpt(trace StackTrace) EntryOption

StackTraceOpt sets the stacktrace if it is still nil.

func TimestampNowOpt

func TimestampNowOpt() EntryOption

TimestampNowOpt sets the timestamp of an entry to time.Now()

func TimestampOpt

func TimestampOpt(t time.Time) EntryOption

TimestampOpt sets the timestamp it is still time.IsZero().

func TracingOpt

func TracingOpt(traceID, spanID string, isSampled bool) EntryOption

TracingOpt sets the tracing data it is not yet set.

type EntryWriter

type EntryWriter interface {
	WriteEntry(Entry)
}

EntryWriter is able to write an entry. It's the concrete "logger". It should handle its own errors.

type FilterWriter

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

FilterWriter is an EntryWriter that will write only logs with the given severity or higher.

func NewFilterWriter

func NewFilterWriter(severity Severity, writer EntryWriter) *FilterWriter

NewFilterWriter returns a new FilterWriter.

func (*FilterWriter) WriteEntry

func (s *FilterWriter) WriteEntry(entry Entry)

WriteEntry implements the EntryWriter interface

type Logger

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

Logger is able to construct entries and write them using an EntryWriter.

func FromContext

func FromContext(ctx context.Context) (*Logger, bool)

FromContext returns the Logger value stored in ctx, if interface{}.

func FromContextOrGlobal

func FromContextOrGlobal(ctx context.Context) *Logger

FromContextOrGlobal returns the Logger value stored in ctx, or the global Logger if none are stored.

func GlobalLogger

func GlobalLogger() *Logger

GlobalLogger return the global logger. If the global logger hasn't been initialized, it returns a default logger printing json output to stdout.

func NewDefaultLogger

func NewDefaultLogger(w EntryWriter) *Logger

NewDefaultLogger creates a new logger with the default stack of entry options: - timestamp set to time.Now() - tracing information from context (either opencensus or telemetry) If you don't need these options, or just need some, you should use NewLogger and chose only the options you need.

func NewLogger

func NewLogger(w EntryWriter, options ...EntryOption) *Logger

NewLogger creates a new logger.

func (*Logger) Alert

func (l *Logger) Alert(msg string, options ...EntryOption)

Alert logs an alert message with additional EntryOptions.

func (*Logger) Critical

func (l *Logger) Critical(msg string, options ...EntryOption)

Critical logs a critical message with additional EntryOptions.

func (*Logger) Debug

func (l *Logger) Debug(msg string, options ...EntryOption)

Debug logs a debug message with additional EntryOptions.

func (*Logger) Emergency

func (l *Logger) Emergency(msg string, options ...EntryOption)

Emergency logs an emergency message with additional EntryOptions.

func (*Logger) Error

func (l *Logger) Error(msg string, options ...EntryOption)

Error logs an error message with additional EntryOptions.

func (*Logger) Info

func (l *Logger) Info(msg string, options ...EntryOption)

Info logs an info message with additional EntryOptions.

func (*Logger) Log

func (l *Logger) Log(msg string, options ...EntryOption)

Log logs a message with additional EntryOptions.

Example
logger := NewDefaultLogger(NewWriter(
	EntryMarshalerFunc(func(entry Entry) []byte {
		return []byte(strings.Join(
			[]string{
				entry.Message,
				entry.Severity.String(),
			},
			"\n",
		))
	}),
	os.Stdout,
))

logger.Log("log message 1")
logger.Error("log message 2")
Output:

log message 1
default
log message 2
error

func (*Logger) LogAny

func (l *Logger) LogAny(v interface{}, options ...EntryOption)

LogAny logs interface{}thing, converting the given value into an entry.

func (*Logger) LogEntry

func (l *Logger) LogEntry(entry Entry)

LogEntry logs an entry.

func (*Logger) Warn

func (l *Logger) Warn(msg string, options ...EntryOption)

Warn logs a warning message with additional EntryOptions.

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a new logger with a new context.

func (*Logger) WithFields

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

WithFields returns a new logger with default labels.

func (*Logger) WithLabels

func (l *Logger) WithLabels(labels map[string]string) *Logger

WithLabels returns a new logger with default labels.

func (*Logger) WithOptions

func (l *Logger) WithOptions(options ...EntryOption) *Logger

WithOptions returns a new logger with additional EntryOptions.

func (*Logger) WithSeverity

func (l *Logger) WithSeverity(severity Severity) *Logger

WithSeverity returns a new logger with a default severity.

type MultiWriter

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

MultiWriter is an EntryWriter that write to all its children.

func NewMultiWriter

func NewMultiWriter(writers ...EntryWriter) *MultiWriter

NewMultiWriter returns a new MultiWriter.

func (*MultiWriter) WriteEntry

func (m *MultiWriter) WriteEntry(entry Entry)

WriteEntry implements the EntryWriter interface.

type Severity

type Severity int

Severity is the severity level of a message. Nothing fancy here, just based on syslog severity levels.

const (
	// DefaultSeverity is the default severity. It means no severity has been set.
	DefaultSeverity Severity = iota
	// EmergencySeverity level: highest level of severity.
	EmergencySeverity
	// AlertSeverity level.Should be corrected ASAP.
	AlertSeverity
	// CriticalSeverity level. Indicates a failure in a primary system.
	CriticalSeverity
	// ErrorSeverity level. Used for errors that should definitely be noted.
	ErrorSeverity
	// WarnSeverity level. Non-critical entries that deserve eyes.
	WarnSeverity
	// InfoSeverity level. Describe normal behavior of the application.
	InfoSeverity
	// DebugSeverity should be used only for debugging purposes. Can contain more verbose information.
	DebugSeverity
)

func (Severity) MarshalJSON

func (s Severity) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Severity) String

func (s Severity) String() string

String implements the fmt.Stringer interface.

type StackTrace

type StackTrace interface {
	fmt.Stringer
	Frames() []runtime.Frame
	Last() (runtime.Frame, bool)
}

StackTrace represents a go stack-trace. It should be able to both return the stacktrace as a string from the debug.Stack() function and the list of frames, as well as the last frame to display This allows the EntryWriter to choose which format they want.

type Writer

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

Writer is able to write entries, transforming them given an EntryMarshaler and writing them using an io.Writer.

func NewWriter

func NewWriter(marshaler EntryMarshaler, writer io.Writer) *Writer

NewWriter returns a new Writer.

func (*Writer) WriteEntry

func (s *Writer) WriteEntry(entry Entry)

WriteEntry implements the EntryWriter interface.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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