clogger

package module
v0.0.0-...-ddce643 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2021 License: MIT Imports: 11 Imported by: 0

README

clogger

Clogger is a context aware, structured logging library written in Go.

It has the following output formatters
  1. GCP Stackdriver
  2. JSON
  3. Terminal (human friendly output)
It offers out of the box tracing
  • OpenCensus
  • OpenTelemetry
How to set up a new logger
package main

import log "github.com/foae/clogger"

func main() {
	// Create a new default logger
	logger := log.NewDefaultLogger()

	// We want the output to be human-readable 
	// – we choose a terminal encoder 
	logger.SetEncoder(&log.TerminalEncoder{})

	// For each and every EVENT, we can choose 
	// decorators or write our own.
	logger.SetEventOptions(log.WithOpenTelemetryTrace(), log.WithExampleEventOption())

	// For each and every LOG ENTRY, we can choose 
	// decorators or write our own.
	logger.SetLogEntryOptions(log.WithOpenCensusSpan())

	// Everything is configured, stored it globally for later use
	log.SetGlobal(logger)
}
How to use the library
  1. Creating new Events
package main

import (
	"context"

	log "github.com/foae/clogger"
)

func handlePOST(ctx context.Context) {
	ctx, event := log.NewEvent(ctx, "Received a new POST request")
	defer event.End()

	// Attach data directly to the event
	event.Set("key", "value")
	event.SetOnErr("key", "value")
	event.SetLabel("key", "value")

	// ... TODO: add more examples, explain what each Set* is doing
}
  1. Logging fields
// consider: import log "github.com/foae/clogger"
// consider: ctx exists

log.Debug(ctx, "A debug statement")
log.With("user_id", userID).Debug(ctx, "A debug statement")
Terminology
  • Events
    • Set
    • SetOnErr
    • SetLabel
  • Log entries
    • Fields
Work In Progress.

Current state: alpha

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(ctx context.Context, msg string)

Debug creates a new log entry with the given severity.

func Debugf

func Debugf(ctx context.Context, msg string, args ...interface{})

Debugf creates a new log entry with the given severity.

func Error

func Error(ctx context.Context, msg string)

func Errorf

func Errorf(ctx context.Context, msg string, args ...interface{})

Errorf creates a new log entry with the given severity.

func Fatal

func Fatal(ctx context.Context, msg string)

Fatal creates a new log entry with the given severity.

func Fatalf

func Fatalf(ctx context.Context, msg string, args ...interface{})

Fatalf creates a new log entry with the given severity.

func Info

func Info(ctx context.Context, msg string)

func Infof

func Infof(ctx context.Context, msg string, args ...interface{})

Infof creates a new log entry with the given severity.

func SetGlobal

func SetGlobal(l Logger)

SetGlobal ...

func Warn

func Warn(ctx context.Context, msg string)

Warn creates a new log entry with the given severity.

func Warnf

func Warnf(ctx context.Context, msg string, args ...interface{})

Warnf creates a new log entry with the given severity.

Types

type DefaultLogger

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

func (*DefaultLogger) EventOptions

func (l *DefaultLogger) EventOptions() []EventOption

func (*DefaultLogger) LogEntryOptions

func (l *DefaultLogger) LogEntryOptions() []LogEntryOption

func (*DefaultLogger) SetEncoder

func (l *DefaultLogger) SetEncoder(enc Encoder)

func (*DefaultLogger) SetEventOptions

func (l *DefaultLogger) SetEventOptions(opts ...EventOption)

func (*DefaultLogger) SetLogEntryOptions

func (l *DefaultLogger) SetLogEntryOptions(opts ...LogEntryOption)

func (*DefaultLogger) StreamEvent

func (l *DefaultLogger) StreamEvent(event *Event)

func (*DefaultLogger) StreamLogEntry

func (l *DefaultLogger) StreamLogEntry(entry *LogEntry)

type Encoder

type Encoder interface {
	EncodeLogEntry(entry *LogEntry) ([]byte, error)
	EncodeEvent(event *Event) ([]byte, error)
}

type Event

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

Event describes a single action that happens at a given time. Typically, it has a short life span where it gathers field, labels and log entries. It must be accompanied by its End method to mark the once of its lifecycle, usually from a defer function call.

func NewEvent

func NewEvent(ctx context.Context, message string) (context.Context, *Event)

func (*Event) End

func (ev *Event) End()

End signals the once of the lifecycle to the event. It will apply all gathered Labels onto all child log entries, and it will finally output using the configured logger instance. Safe to be called multiple times.

func (*Event) Set

func (ev *Event) Set(key string, value interface{}) Eventful

Set registers a key/value pair for the current event. These pairs are not being passed down to child log entries.

func (*Event) SetLabel

func (ev *Event) SetLabel(key string, value interface{}) Eventful

SetLabel registers a key/value pair as a label. This pair will then be passed down and stamped/written onto all child log entries that this event might collect throughout its lifecycle.

func (*Event) SetOnErr

func (ev *Event) SetOnErr(key string, value interface{}) Eventful

SetOnErr registers a key/value pair for the current event that will be logged (outputted) only in case the severity is raised over the Info threshold e.g. by registering an error log entry. fields Set with this method get logged only if an error occurs during the event's lifecycle. Otherwise, these are discarded.

type EventOption

type EventOption func(ctx context.Context, event *Event)

func WithExampleEventOption

func WithExampleEventOption() EventOption

func WithOpenCensusTrace

func WithOpenCensusTrace() EventOption

func WithOpenTelemetryTrace

func WithOpenTelemetryTrace() EventOption

type Eventful

type Eventful interface {
	Set(key string, value interface{}) Eventful
	SetOnErr(key string, value interface{}) Eventful
	SetLabel(key string, value interface{}) Eventful
}

func Set

func Set(ctx context.Context, key string, value interface{}) Eventful
Setters (Eventful interface)

Set decorates the event's fields with the given key/value pair. These fields are outputted only in the event entry itself, and it is not passed down to its child log entries (use SetLabel for that). Set Should only be used if you have started an event in your call chain and passed ctx. If no event was found, it will create (ad-hoc) an "Unnamed event" with its severity raised to Warning. All subsequent calls to the Eventful interface will be attached to this event, whether it existed or was created ad-hoc.

func SetLabel

func SetLabel(ctx context.Context, key string, value interface{}) Eventful

SetLabel decorates the event's labels with the given key/value pair. Labels pass down their fields (key/value pairs) to all the event's child log entries. SetLabel Should only be used if you have started an event in your call chain and passed ctx. If no event was found, it will create (ad-hoc) an "Unnamed event" with its severity raised to Warning. All subsequent calls to the Eventful interface will be attached to this event, whether it existed or was created ad-hoc.

func SetOnErr

func SetOnErr(ctx context.Context, key string, value interface{}) Eventful

SetOnErr decorates the event's error fields with the given key/value pair. Error fields are skipped (not outputted) if "nothing happens", meaning if no log entry raises the severity level over the configured threshold. It is generally useful to log additional fields but only when an error occurs. SetOnErr Should only be used if you have started an event in your call chain and passed ctx. If no event was found, it will create (ad-hoc) an "Unnamed event" with its severity raised to Warning. All subsequent calls to the Eventful interface will be attached to this event, whether it existed or was created ad-hoc.

type JSONEncoder

type JSONEncoder struct{}

func (*JSONEncoder) EncodeEvent

func (j *JSONEncoder) EncodeEvent(event *Event) ([]byte, error)

func (*JSONEncoder) EncodeLogEntry

func (j *JSONEncoder) EncodeLogEntry(entry *LogEntry) ([]byte, error)

type LogEntry

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

LogEntry defines the structure of a single, unitary log entry.

func (*LogEntry) Debug

func (e *LogEntry) Debug(ctx context.Context, message string)

Debug ...

func (*LogEntry) Debugf

func (e *LogEntry) Debugf(ctx context.Context, message string, args ...interface{})

Debugf ...

func (*LogEntry) Error

func (e *LogEntry) Error(ctx context.Context, message string)

Error ...

func (*LogEntry) Errorf

func (e *LogEntry) Errorf(ctx context.Context, message string, args ...interface{})

Errorf ...

func (*LogEntry) Fatal

func (e *LogEntry) Fatal(ctx context.Context, message string)

Fatal ...

func (*LogEntry) Fatalf

func (e *LogEntry) Fatalf(ctx context.Context, message string, args ...interface{})

Fatalf ...

func (*LogEntry) Info

func (e *LogEntry) Info(ctx context.Context, message string)

Info ...

func (*LogEntry) Infof

func (e *LogEntry) Infof(ctx context.Context, message string, args ...interface{})

Infof ...

func (*LogEntry) Warn

func (e *LogEntry) Warn(ctx context.Context, message string)

Warn ...

func (*LogEntry) Warnf

func (e *LogEntry) Warnf(ctx context.Context, message string, args ...interface{})

Warnf ...

func (*LogEntry) With

func (e *LogEntry) With(key string, value interface{}) Loggable

With ...

type LogEntryOption

type LogEntryOption func(ctx context.Context, entry *LogEntry)

func WithExampleEntryOption

func WithExampleEntryOption() LogEntryOption

func WithOpenCensusSpan

func WithOpenCensusSpan() LogEntryOption

func WithOpenTelemetrySpan

func WithOpenTelemetrySpan() LogEntryOption

type Loggable

type Loggable interface {
	With(key string, value interface{}) Loggable

	Debug(ctx context.Context, message string)
	Debugf(ctx context.Context, message string, args ...interface{})

	Info(ctx context.Context, message string)
	Infof(ctx context.Context, message string, args ...interface{})

	Warn(ctx context.Context, message string)
	Warnf(ctx context.Context, message string, args ...interface{})

	Error(ctx context.Context, message string)
	Errorf(ctx context.Context, message string, args ...interface{})

	Fatal(ctx context.Context, message string)
	Fatalf(ctx context.Context, message string, args ...interface{})
}

func With

func With(key string, value interface{}) Loggable

With registers a set of fields

type Logger

type Logger interface {
	StreamLogEntry(e *LogEntry)
	SetLogEntryOptions(opts ...LogEntryOption)
	LogEntryOptions() []LogEntryOption

	StreamEvent(ev *Event)
	SetEventOptions(opts ...EventOption)
	EventOptions() []EventOption

	SetEncoder(enc Encoder)
}

func NewDefaultLogger

func NewDefaultLogger() Logger

type Severity

type Severity int

Severity ...

const (
	SeverityDebug Severity = iota
	SeverityInfo
	SeverityWarn
	SeverityError
	SeverityCritical
)

func (Severity) String

func (s Severity) String() string

String implements the stringer interface.

type StackdriverEncoder

type StackdriverEncoder struct{}

https://cloud.google.com/logging/docs/structured-logging

{
  "severity":"ERROR",
  "message":"There was an error in the application.",
  "httpRequest":{
	"requestMethod":"GET"
  },
  "time":"2020-10-12T07:20:50.52Z",
  "logging.googleapis.com/labels":{
	"user_label_1":"value_1",
	"user_label_2":"value_2"
  },
  "logging.googleapis.com/sourceLocation":{
	"file":"get_data.py",
	"line":"142",
	"function":"getData"
  },
  "logging.googleapis.com/spanId":"000000000000004a",
  "logging.googleapis.com/trace":"projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824",
  "logging.googleapis.com/trace_sampled":false
}

func (*StackdriverEncoder) EncodeEvent

func (j *StackdriverEncoder) EncodeEvent(event *Event) ([]byte, error)

func (*StackdriverEncoder) EncodeLogEntry

func (j *StackdriverEncoder) EncodeLogEntry(entry *LogEntry) ([]byte, error)

type TerminalEncoder

type TerminalEncoder struct{}

func (*TerminalEncoder) EncodeEvent

func (t *TerminalEncoder) EncodeEvent(event *Event) ([]byte, error)

func (*TerminalEncoder) EncodeLogEntry

func (t *TerminalEncoder) EncodeLogEntry(entry *LogEntry) ([]byte, error)

Jump to

Keyboard shortcuts

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