gzap

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2018 License: BSD-3-Clause Imports: 12 Imported by: 0

README

gzap - Graylog Integrated Zap Logger

GoDoc CircleCI codecov Go Report Card

Gzap provide fast structured leveled logging using zap, and a TCP/UDP Graylog logsink (TLS supported). Both zap and Graylog librarys are versioned locked within the applications so no other external dependencies required.

Getting Stated

To use gzap, first import it:

import "gopkg.in/dailymuse/gzap.v1"

The Graylog logsink is only enabled for Production and Staging environments. So you'll need to set a GRAYLOG_ENV environment variable with either of the following correlating states.

GRAYLOG_ENV Environment Graylog enabled?
0 Test (no-op logger)
1 Dev
2 Staging
3 Production
Environment Variables

To properly use gzap you'll need to set your configurations via Environment variables. The following are configurable Envs:

Env Name Description
GRAYLOG_ENV A number 0 - 3 describing the Graylog loggin environment you wish to use (Refrence table above)
GRAYLOG_HOST Hostname that your graylog is currently listening on example.graylog.com
ENABLE_DATADOG_JSON_FORMATTER set to "true" to enable json formatted logs.
Internal API

The logger that is publicly exposed is the zap Logger. You can reference what log levels are available for use here). Below are a few examples:

func (log *Logger) DPanic(msg string, fields ...zapcore.Field)
func (log *Logger) Debug(msg string, fields ...zapcore.Field)
func (log *Logger) Error(msg string, fields ...zapcore.Field)
func (log *Logger) Fatal(msg string, fields ...zapcore.Field)
func (log *Logger) Info(msg string, fields ...zapcore.Field)
func (log *Logger) Panic(msg string, fields ...zapcore.Field)
func (log *Logger) Warn(msg string, fields ...zapcore.Field)

All zap fields needed for logging are also exposed by gzap.

gzap.Logger.Error("this is an example Error log",
        gzap.String("variable", "some-variable-here"),
)

For any other information please take a look at the gzap Godoc.

Example Usage
package main

import (
    "time"

    "gopkg.in/dailymuse/gzap.v1"
)

func main() {
    // Instantiate a global logger.
    if err := gzap.InitLogger(); err != nil {
        panic(err)
    }

    // Example Info log.
    gzap.Logger.Info("this is an example Info log",
        gzap.String("process name", "some-fake-name"),
        gzap.Int64("expectedDocs", int64(255)),
        gzap.Int64("docsUploaded", int64(100)),
    )

    // Example Error log.
    gzap.Logger.Error("this is an example Error log",
        gzap.Error(errors.New("example error")),
        gzap.String("index name", "my-full-index-name"),
        gzap.Float64("time elapsed", float64(1002)),
    )

    // Example Debug log.
    gzap.Logger.Debug("this is an example Debug log",
        gzap.String("variable", "some-variable-here"),
    )
}
Important info
Contributing

In order to contribute you'll need to have a valid go environment setup.

If you need to install go, see installation instructions here.

Tests Logs are a no-op

Tests that run application code containing logs will not print those logs by default. The Test logger is a no-op to reduce noise during testing.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var Logger = getLogger()

Logger is the global logger for the application. Upon first initalization of the logger all calls to 'getLogger' are memoized with the instantiated 'logger'.

Functions

func Any

func Any(key string, value interface{}) zapcore.Field

Any takes a key and an arbitrary value and chooses the best way to represent them as a field, falling back to a reflection-based approach only if necessary.

Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between them. To minimize surprises, []byte values are treated as binary blobs, byte values are treated as uint8, and runes are always treated as integers.

func Array

func Array(key string, val zapcore.ArrayMarshaler) zapcore.Field

Array constructs a field with the given key and ArrayMarshaler. It provides a flexible, but still type-safe and efficient, way to add array-like types to the logging context. The struct's MarshalLogArray method is called lazily.

func Binary

func Binary(key string, val []byte) zapcore.Field

Binary constructs a field that carries an opaque binary blob.

Binary data is serialized in an encoding-appropriate format. For example, zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, use ByteString.

func Bool

func Bool(key string, val bool) zapcore.Field

Bool constructs a field that carries a bool.

func Bools

func Bools(key string, bs []bool) zapcore.Field

Bools constructs a field that carries a slice of bools.

func ByteString

func ByteString(key string, val []byte) zapcore.Field

ByteString constructs a field that carries UTF-8 encoded text as a []byte. To log opaque binary blobs (which aren't necessarily valid UTF-8), use Binary.

func ByteStrings

func ByteStrings(key string, bss [][]byte) zapcore.Field

ByteStrings constructs a field that carries a slice of []byte, each of which must be UTF-8 encoded text.

func Complex128

func Complex128(key string, val complex128) zapcore.Field

Complex128 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex128 to interface{}).

func Complex128s

func Complex128s(key string, nums []complex128) zapcore.Field

Complex128s constructs a field that carries a slice of complex numbers.

func Complex64

func Complex64(key string, val complex64) zapcore.Field

Complex64 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex64 to interface{}).

func Complex64s

func Complex64s(key string, nums []complex64) zapcore.Field

Complex64s constructs a field that carries a slice of complex numbers.

func Duration

func Duration(key string, val time.Duration) zapcore.Field

Duration constructs a field with the given key and value. The encoder controls how the duration is serialized.

func Durations

func Durations(key string, ds []time.Duration) zapcore.Field

Durations constructs a field that carries a slice of time.Durations.

func Error

func Error(err error) zapcore.Field

Error is shorthand for the common idiom NamedError("error", err).

func Errors

func Errors(key string, errs []error) zapcore.Field

Errors constructs a field that carries a slice of errors.

func Float32

func Float32(key string, val float32) zapcore.Field

Float32 constructs a field that carries a float32. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Float32s

func Float32s(key string, nums []float32) zapcore.Field

Float32s constructs a field that carries a slice of floats.

func Float64

func Float64(key string, val float64) zapcore.Field

Float64 constructs a field that carries a float64. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Float64s

func Float64s(key string, nums []float64) zapcore.Field

Float64s constructs a field that carries a slice of floats.

func InitLogger added in v1.1.1

func InitLogger() error

InitLogger initializes a global Logger based upon your env configurations.

Example
if err := InitLogger(); err != nil {
	panic(err)
}

defer Logger.Sync()

Logger.Info("this is a test info log")
Output:

func Int

func Int(key string, val int) zapcore.Field

Int constructs a field with the given key and value.

func Int16

func Int16(key string, val int16) zapcore.Field

Int16 constructs a field with the given key and value.

func Int16s

func Int16s(key string, nums []int16) zapcore.Field

Int16s constructs a field that carries a slice of integers.

func Int32

func Int32(key string, val int32) zapcore.Field

Int32 constructs a field with the given key and value.

func Int32s

func Int32s(key string, nums []int32) zapcore.Field

Int32s constructs a field that carries a slice of integers.

func Int64

func Int64(key string, val int64) zapcore.Field

Int64 constructs a field with the given key and value.

func Int64s

func Int64s(key string, nums []int64) zapcore.Field

Int64s constructs a field that carries a slice of integers.

func Int8

func Int8(key string, val int8) zapcore.Field

Int8 constructs a field with the given key and value.

func Int8s

func Int8s(key string, nums []int8) zapcore.Field

Int8s constructs a field that carries a slice of integers.

func Ints

func Ints(key string, nums []int) zapcore.Field

Ints constructs a field that carries a slice of integers.

func NamedError

func NamedError(key string, err error) zapcore.Field

NamedError constructs a field that lazily stores err.Error() under the provided key. Errors which also implement fmt.Formatter (like those produced by github.com/pkg/errors) will also have their verbose representation stored under key+"Verbose". If passed a nil error, the field is a no-op.

For the common case in which the key is simply "error", the Error function is shorter and less repetitive.

func Namespace

func Namespace(key string) zapcore.Field

Namespace creates a named, isolated scope within the logger's context. All subsequent fields will be added to the new namespace.

This helps prevent key collisions when injecting loggers into sub-components or third-party libraries.

func Object

func Object(key string, val zapcore.ObjectMarshaler) zapcore.Field

Object constructs a field with the given key and ObjectMarshaler. It provides a flexible, but still type-safe and efficient, way to add map- or struct-like user-defined types to the logging context. The struct's MarshalLogObject method is called lazily.

func Reflect

func Reflect(key string, val interface{}) zapcore.Field

Reflect constructs a field with the given key and an arbitrary object. It uses an encoding-appropriate, reflection-based function to lazily serialize nearly any object into the logging context, but it's relatively slow and allocation-heavy. Outside tests, Any is always a better choice.

If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect includes the error message in the final log output.

func Skip

func Skip() zapcore.Field

Skip constructs a no-op field, which is often useful when handling invalid inputs in other Field constructors.

func Stack

func Stack(key string) zapcore.Field

Stack constructs a field that stores a stacktrace of the current goroutine under provided key. Keep in mind that taking a stacktrace is eager and expensive (relatively speaking); this function both makes an allocation and takes about two microseconds.

func String

func String(key string, val string) zapcore.Field

String constructs a field with the given key and value.

func Stringer

func Stringer(key string, val fmt.Stringer) zapcore.Field

Stringer constructs a field with the given key and the output of the value's String method. The Stringer's String method is called lazily.

func Strings

func Strings(key string, ss []string) zapcore.Field

Strings constructs a field that carries a slice of strings.

func Time

func Time(key string, val time.Time) zapcore.Field

Time constructs a zapcore.Field with the given key and value. The encoder controls how the time is serialized.

func Times

func Times(key string, ts []time.Time) zapcore.Field

Times constructs a field that carries a slice of time.Times.

func Uint

func Uint(key string, val uint) zapcore.Field

Uint constructs a field with the given key and value.

func Uint16

func Uint16(key string, val uint16) zapcore.Field

Uint16 constructs a field with the given key and value.

func Uint16s

func Uint16s(key string, nums []uint16) zapcore.Field

Uint16s constructs a field that carries a slice of unsigned integers.

func Uint32

func Uint32(key string, val uint32) zapcore.Field

Uint32 constructs a field with the given key and value.

func Uint32s

func Uint32s(key string, nums []uint32) zapcore.Field

Uint32s constructs a field that carries a slice of unsigned integers.

func Uint64

func Uint64(key string, val uint64) zapcore.Field

Uint64 constructs a field with the given key and value.

func Uint64s

func Uint64s(key string, nums []uint64) zapcore.Field

Uint64s constructs a field that carries a slice of unsigned integers.

func Uint8

func Uint8(key string, val uint8) zapcore.Field

Uint8 constructs a field with the given key and value.

func Uint8s

func Uint8s(key string, nums []uint8) zapcore.Field

Uint8s constructs a field that carries a slice of unsigned integers.

func Uintptr

func Uintptr(key string, val uintptr) zapcore.Field

Uintptr constructs a field with the given key and value.

func Uintptrs

func Uintptrs(key string, us []uintptr) zapcore.Field

Uintptrs constructs a field that carries a slice of pointer addresses.

func Uints

func Uints(key string, us []uint) zapcore.Field

Uints constructs a field that carries a slice of unsigned integers.

Types

type Config

type Config interface {
	// contains filtered or unexported methods
}

Config is an interface representing all the logging configurations accessible via environment

type EnvConfig added in v1.1.1

type EnvConfig struct{}

EnvConfig represents all the logger configurations available when instaniating a new Logger.

type GelfCore

type GelfCore struct {
	Graylog Graylog
	Context []zapcore.Field
	// contains filtered or unexported fields
}

GelfCore implements the https://godoc.org/go.uber.org/zap/zapcore#Core interface Messages are written to a graylog endpoint using the GELF format + protocol

func NewGelfCore

func NewGelfCore(cfg Config, gl Graylog) GelfCore

NewGelfCore creates a new GelfCore with empty context.

func (GelfCore) Check

func (gc GelfCore) Check(entry zapcore.Entry, checkedEntry *zapcore.CheckedEntry) *zapcore.CheckedEntry

Check determines whether the supplied entry should be logged.

func (GelfCore) Enabled

func (gc GelfCore) Enabled(level zapcore.Level) bool

Enabled only enables info messages and above.

func (GelfCore) Sync

func (gc GelfCore) Sync() error

Sync is a no-op.

func (GelfCore) With

func (gc GelfCore) With(fields []zapcore.Field) zapcore.Core

With adds structured context to the logger.

func (GelfCore) Write

func (gc GelfCore) Write(entry zapcore.Entry, fields []zapcore.Field) error

Write writes messages to the configured Graylog endpoint.

type Graylog

type Graylog interface {
	Close() error
	Send(graylog.Message) error
}

Graylog is a unifying interface for using the internal Graylog package 'github.com/Devatoria/go-graylog', while also being able to use Mocks in it's place.

func NewGraylog

func NewGraylog(cfg Config) (Graylog, error)

NewGraylog returns a new Graylog instance.

type GraylogConstructor added in v1.1.1

type GraylogConstructor func(cfg Config) (Graylog, error)

type LevedLogger added in v1.1.1

type LevedLogger func(msg string, fields ...zapcore.Field)

LevedLogger is a unifying type for all of the exported zap leveled loggers, Info, Warn, Error, Debug.

type MockEnvConfig added in v1.1.1

type MockEnvConfig struct {
	mock.Mock
}

MockEnvConfig represents all the logger configurations available when instaniating a new Logger via a mock.

type MockGraylog

type MockGraylog struct {
	mock.Mock
}

MockGraylog is a mock Graylog struct used for testing.

func NewMockGraylog

func NewMockGraylog() MockGraylog

NewMockGraylog returns a new MockGraylog struct.

func (*MockGraylog) Close

func (m *MockGraylog) Close() error

Close closes the opened connections of the given client

func (*MockGraylog) Send

func (m *MockGraylog) Send(msg graylog.Message) error

Send writes the given message to the given graylog client

Jump to

Keyboard shortcuts

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