hatchet

package module
v0.0.0-...-91eccfc Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2020 License: BSD-3-Clause Imports: 12 Imported by: 1

README

Build Status Go Report Card Go Docs

Hatchet

Log pipelining for Go. See the Go Docs for more info.

Documentation

Overview

Package hatchet is a logging framework.

Index

Constants

This section is empty.

Variables

View Source
var (
	CriticalLevel = "critical"
	ErrorLevel    = "error"
	WarningLevel  = "warning"
	InfoLevel     = "info"
	DebugLevel    = "debug"
)

Hatchet defines some common log levels. These are used throughout the package and should be used by packages that extend Hatchet. they may be set to suit the developer's needs. These levels are:

View Source
var (
	// Holds the log message. Value is typically a string.
	Message = "message"

	// Holds the timestamp. Value is typically a time.Time.
	Time = "time"

	// Holds the log level. Value is typically a string.
	Level = "level"

	// Holds the error. Value is typically an error. Usually accompanied by a
	// level of warning or higher.
	Error = "error"

	// Holds the PID of the process. Typically an int.
	PID = "pid"

	// Holds the name of the process. Typically a string.
	// The value for this is the name of the process as launched from the command line
	// ex:
	//     ENV=zd ./foo arg1 arg2 yields `foo` as the process name
	Process = "process"

	// Holds the name of the host running the process. Typically a string.
	Hostname = "hostname"

	// Holds the name of the services image.
	// The value for this is read in from a Consul env variable.
	// This name can differ from the Process name.
	ImageName = "image"
)

Hatchet globally defines some common field names. They are used throughout the package and should be packages that extend Hatchet. They may be set to suit the developer's needs. These fields are:

View Source
var (
	// ErrTimeout is returned to indicate a timeout.
	ErrTimeout = errors.New("operation timed out")
)

Functions

func LevelValue

func LevelValue(level string) int

LevelValue returns an integer value for the level. Higher values are higher in severity than lower values. A value of 0 is returned for levels which are unrecognized.

func PrintFailure

func PrintFailure(log map[string]interface{}, err error)

PrintFailure is used to indicate a failure which causes a log to be discarded. The error and discarded log are printed to stderr.

Types

type L

type L map[string]interface{}

L is used to pass structured log data to a Logger.

func (L) Copy

func (l L) Copy() L

Copy returns a shallow copy of the log.

func (L) CopyTo

func (l L) CopyTo(cp L)

CopyTo copies fields from this log to another.

func (L) Error

func (l L) Error() error

Error returns the value of the log's error field.

func (L) Level

func (l L) Level() string

Level returns the value of the log's level field. An empty string is returned if it is not set.

func (L) LevelValue

func (l L) LevelValue() int

LevelValue returns the integer value of a log level. A 0 is returned if not set or unrecognized. See `LevelValue` for more detail.

func (L) Message

func (l L) Message() string

Message returns the value of the log's message field.

func (L) Time

func (l L) Time() time.Time

Time returns the timestamp of the log. If the log has no timestamp the time.Time zero value is returned. The time is extracted from the TimeField log field. It is expected to be either a time.Time or an integer containing a Unix timestamp.

type LeveledLogger

type LeveledLogger struct {
	Logger
	DefaultLevel string
}

LeveledLogger ensures all message moving through it have a log level attached.

func Levelize

func Levelize(logger Logger) *LeveledLogger

Levelize creates a LeveledLogger which logs messages to the given logger.

func (*LeveledLogger) Critical

func (l *LeveledLogger) Critical(a ...interface{})

Critical calls `Print` with `CriticalLevel`.

func (*LeveledLogger) Criticalf

func (l *LeveledLogger) Criticalf(format string, a ...interface{})

Criticalf calls `Printf` with `CriticalLevel`.

func (*LeveledLogger) Debug

func (l *LeveledLogger) Debug(a ...interface{})

Debug calls `Print` with `DebugLevel`.

func (*LeveledLogger) Debugf

func (l *LeveledLogger) Debugf(format string, a ...interface{})

Debugf calls `Printf` with `DebugLevel`.

func (*LeveledLogger) Error

func (l *LeveledLogger) Error(a ...interface{})

Error calls `Print` with `ErrorLevel`.

func (*LeveledLogger) Errorf

func (l *LeveledLogger) Errorf(format string, a ...interface{})

Errorf calls `Printf` with `ErrorLevel`.

func (*LeveledLogger) Info

func (l *LeveledLogger) Info(a ...interface{})

Info calls `Print` with `InfoLevel`.

func (*LeveledLogger) Infof

func (l *LeveledLogger) Infof(format string, a ...interface{})

Infof calls `Printf` with `InfoLevel`.

func (*LeveledLogger) Log

func (l *LeveledLogger) Log(log map[string]interface{})

Log a message. Set the log level if it is not already set. The level is set to ErrorLevel if the log contains an error or InfoLevel otherwise.

func (*LeveledLogger) LogWithLevel

func (l *LeveledLogger) LogWithLevel(level string, log map[string]interface{})

LogWithLevel logs a message at the given level. If the message already has a level it is overwitten.

func (*LeveledLogger) Print

func (l *LeveledLogger) Print(level string, a ...interface{})

Print works like `fmt.Print` but sends the message to the logger.

func (*LeveledLogger) Printf

func (l *LeveledLogger) Printf(level, format string, a ...interface{})

Printf works like `fmt.Printf` but sends the message to the logger.

func (*LeveledLogger) Warning

func (l *LeveledLogger) Warning(a ...interface{})

Warning calls `Print` with `WarningLevel`.

func (*LeveledLogger) Warningf

func (l *LeveledLogger) Warningf(format string, a ...interface{})

Warningf calls `Printf` with `WarningLevel`.

type Logger

type Logger interface {
	// Log send a structured message to the logger.
	Log(map[string]interface{})

	// Close the logger. Cleans up resources associated with the logger
	// including any loggers encapsulated by this logger.
	Close() error
}

Logger implements field-based logging.

func AppInfo

func AppInfo(logger Logger) Logger

AppInfo appends application information to a log. These include pid, process name, and hostname.

func Async

func Async(logger Logger) Logger

Async wraps a logger with asynchronous functionality. An asynchronous logger does not block on calls to Log. Calling Close blocks until all asynchronous actions complete.

func Broadcast

func Broadcast(loggers ...Logger) Logger

Broadcast creates a logger which logs messages to all of the given loggers. Log messages are copied so as to avoid cross-talk and race conditions.

func Buffer

func Buffer(logger Logger, size int) Logger

Buffer creates a logger which buffers logs to the child logger. It allocates a buffer of the provided size. Calls to Log queue items into the buffer. Order is maintained. Logs are taken off of the buffer and sent to the child logger asynchronously. This allows calls to Log to be non-blocking so long as the buffer is not full. If the buffer fills then calls to Log will block until capacity is available.

func BufferWithDiscard

func BufferWithDiscard(logger Logger, size int) Logger

BufferWithDiscard works like Buffer but will discard logs if the buffer is full. This prevents calls to Log from blocking at the risk of discarding logs.

func Console

func Console(wr io.Writer) Logger

Console creates a logger that formats messages for logging to the console. The logger does not close the underlying writer when Close is called.

func ConsoleWithTemplate

func ConsoleWithTemplate(wr io.Writer, templateText string) (Logger, error)

ConsoleWithTemplate returns a console logger that formats its messages with the given template.

func Fields

func Fields(logger Logger, fields map[string]interface{}, replace bool) Logger

Fields creates a logger that sets the given fields on each log message. The logger replaces existing fields if replace is set to true.

func Filter

func Filter(logger Logger, predicate Predicate) Logger

Filter discards logs which do not match the predicate.

func JSON

func JSON(wr io.Writer) Logger

JSON creates a logger which encodes messages as JSON and writes them to the given writer, one message per line. The "error" field is converted to a string before writing. Empty logs are discarded. The writer is closed when `Close` is called on the logger.

func Null

func Null() Logger

Null discards all logs.

func Test

func Test(t T) Logger

Test creates a logger which encode logs as JSON and writes them to the given T object.

func Timestamp

func Timestamp(logger Logger) Logger

Timestamp creates a logger that adds a timestamp to each log. The timestamp is a time.Time holding the current UTC time. It overwrites any existing value.

func TimestampInLocation

func TimestampInLocation(logger Logger, location *time.Location) Logger

TimestampInLocation creates a logger that adds a timestamp to each log. The timestamp is a time.Time holding the current time in the provided location. If the location is nil UTC is used. Existing timestamps are overwritten.

type MockLogger

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

MockLogger stores logs for testing. Operations on MockLogger are thread safe.

func Mock

func Mock() *MockLogger

Mock returns a logger suitable for use in mocks.

func (*MockLogger) Close

func (l *MockLogger) Close() error

Close does nothing and returns nil.

func (*MockLogger) Closed

func (l *MockLogger) Closed() bool

Closed returns true if Close has been called.

func (*MockLogger) First

func (l *MockLogger) First() L

First returns the first log sent through the mock or nil of none have been sent.

func (*MockLogger) Last

func (l *MockLogger) Last() L

Last returns the first log sent through the mock or nil of none have been sent.

func (*MockLogger) Log

func (l *MockLogger) Log(log map[string]interface{})

Log appends a log to the mock's array of logs.

func (*MockLogger) Logs

func (l *MockLogger) Logs() []L

Logs returns the logs that were sent to the logger.

type Predicate

type Predicate func(map[string]interface{}) bool

Predicate is a function used to match logs.

func IsEqual

func IsEqual(field string, value interface{}) Predicate

IsEqual creates a predicate which checks the equality of a field against the given value. This wraps a basic Go equality check.

func IsLevelAtLeast

func IsLevelAtLeast(level string) Predicate

IsLevelAtLeast creates a predicate that checks if a log's level is at least as severe as the provided level. If no level exists it is assumed to be InfoLevel.

func IsLevelAtMost

func IsLevelAtMost(level string) Predicate

IsLevelAtMost creates a predicate that checks if a log's level is no more severe as the provided level. If no level exists it is assumed to be InfoLevel.

func IsSet

func IsSet(field string) Predicate

IsSet is a predicate which returns true when a log message has the given field.

func Not

func Not(predicate Predicate) Predicate

Not creates a predicate with negates the result of the given predicate.

type StandardLogger

type StandardLogger struct {
	Logger
}

StandardLogger extends a Logger with functions from the standard library logger.

func Standardize

func Standardize(l Logger) *StandardLogger

Standardize creates a StandardLogger from the provided Logger.

func (*StandardLogger) Fatal

func (l *StandardLogger) Fatal(v ...interface{})

Fatal is equivalent to l.Print() followed by a call to os.Exit(1).

func (*StandardLogger) Fatalf

func (l *StandardLogger) Fatalf(f string, v ...interface{})

Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).

func (*StandardLogger) Fatalln

func (l *StandardLogger) Fatalln(v ...interface{})

Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).

func (*StandardLogger) Output

func (l *StandardLogger) Output(calldepth int, s string) error

Output writes the output for a logging event. It formats the message as a JSON object with a single field, `message`, set to `s`.

func (*StandardLogger) OutputWithLevel

func (l *StandardLogger) OutputWithLevel(calldepth int, s string, lvl string) error

OutputWithLevel writes the output for a logging event. It formats the message as a JSON object with two fields, `message`, set to `s` and "level" set to `lvl`.

Preserving the level allows underlying loggers with knowledge of Level values to function properly.

func (*StandardLogger) Panic

func (l *StandardLogger) Panic(v ...interface{})

Panic is equivalent to l.Print() followed by a call to panic().

func (*StandardLogger) Panicf

func (l *StandardLogger) Panicf(f string, v ...interface{})

Panicf is equivalent to l.Printf() followed by a call to panic().

func (*StandardLogger) Panicln

func (l *StandardLogger) Panicln(v ...interface{})

Panicln is equivalent to l.Println() followed by a call to panic().

func (*StandardLogger) Print

func (l *StandardLogger) Print(v ...interface{})

Print calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Print.

func (*StandardLogger) Printf

func (l *StandardLogger) Printf(f string, v ...interface{})

Printf calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Printf.

func (*StandardLogger) Println

func (l *StandardLogger) Println(v ...interface{})

Println calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Println.

func (*StandardLogger) Write

func (l *StandardLogger) Write(p []byte) (n int, err error)

Write bytes to the logger. Converts `p` to a string using `Sprintf` and called `Output`.

type T

type T interface {
	Log(args ...interface{})
}

T is used to adapt a testing.T or testing.B object for logging.

type Writer

type Writer struct {
	Logger
	Field      string
	BufferSize int
	// contains filtered or unexported fields
}

Writer is an io.Writer which sends each written line to the underlying Logger.

By default the emitted log contains the line in the "message" field. This may be changed by setting Field to a non-empty value.

Writes are buffered in order to allow a line to be written over multiple writes. By default the maximum size of this buffer is 256 bytes. This may be changed by setting BufferSize. When the buffer reaches its max size without seeing a newline its contents are emitted to a log.

The buffer may be flushed to a log by calling `Flush`. `Flush` is called by `Close` prior to closing the underlying logger.

func NewWriter

func NewWriter(logger Logger) *Writer

NewWriter creates a log writer with default field and buffer size.

func (*Writer) Close

func (w *Writer) Close() error

Close flushes the buffer and closes the underlying logger.

func (*Writer) Flush

func (w *Writer) Flush()

Flush emits the current contents of the buffer to a log and clears the buffer.

func (*Writer) Write

func (w *Writer) Write(b []byte) (int, error)

Write appends data to the buffer. The buffer is flushed when a newline is written or when the buffer's capacity is reached.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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