kvlog

package module
v0.0.0-...-77ca0c1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2018 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Key=Value Log Formatter for Logrus

GoDoc Build Status

This package provides a text formatting type for Logrus.
It is similar to the text formatter that comes with Logrus, but is focused on compatibility with logging systems such as Splunk.

It provides a number of features

  • All fields logged as key=value format (which Splunk automatically extracts).
  • Fields keys are sorted into lexicographical order.
  • Important/primary fields can be pinned to the start of each log entry so they're easy to spot.
  • Constant fields can be defined within the formatter. For example, a build commit hash can be included in every log entry automatically.
  • All string types are wrapped in quotes automatically.
  • Types can define their own marshaler for custom behaviour
  • Compound types can return multiple key/value pairs by implementing a Loggable interface.
  • The calling function can optionally be included in every log entry.

Example usage:

log.SetFormatter(
    kvlog.New(
        // include the calling function name
        kvlog.IncludeCaller(), 

        // ensure action and status always appear first
        kvlog.WithPrimaryFields("action", "status")))

log.WithFields(log.Fields{
    "action":          "user_login",
    "status":          "ok",
    "username":        "joe_user",
    "email":           "joe@example.com",
    "active_sessions": 4,
}).Info("User logged in")

// Output:
//  2017-01-02T12:00:00.000Z ll="info" srcfnc="Example" srcline=29 action="user_login" status="ok" active_sessions=4 email="joe@example.com" username="joe_user" _msg="User logged in"

Documentation

Overview

Package kvlog implement a key=value log formatter for the logrus logging package.

It can optionally include the calling function name and line number, include constant values in every line and promote certain primary keys to the beginning of each line. All other keys are sorted into alphabetical order for easy scanning, with the human-readnable description at the end of each line.

eg.

2017-07-09T17:00:05.460Z ll="info" srcfnc="(*MessageProcessor).handleDelivery" action="deliver_msg" status="ok" msg_count=1 _msg="delivered message ok"

This provides a format that's human-readable, yet automatically extracted by tools such as Splunk.

Example
package main

import (
	"bytes"
	"fmt"
	"regexp"

	log "github.com/Sirupsen/logrus"
	"github.com/gwatts/kvlog"
)

func main() {
	var buf bytes.Buffer

	log.SetOutput(&buf)
	log.SetFormatter(
		kvlog.New(
			kvlog.IncludeCaller(),
			kvlog.WithPrimaryFields("action", "status")))

	log.WithFields(log.Fields{
		"action":          "user_login",
		"status":          "ok",
		"username":        "joe_user",
		"email":           "joe@example.com",
		"active_sessions": 4,
	}).Info("User logged in")

	// replace the timestamp so the output is consistent
	output := "2017-01-02T12:00:00.000Z " + buf.String()[25:]

	// replace srcline so tests aren't sensitive to exact line number
	output = regexp.MustCompile(`srcline=\d+`).ReplaceAllLiteralString(output, `srcline=100`)

	fmt.Println(output)
}
Output:
2017-01-02T12:00:00.000Z ll="info" srcfnc="Example" srcline=100 action="user_login" status="ok" active_sessions=4 email="joe@example.com" username="joe_user" _msg="User logged in"

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config func(kvf *Formatter)

Config represents a configuration function to be passed to New.

func IncludeCaller

func IncludeCaller() Config

IncludeCaller causes the Formatter to include the calling function name in each log entry.

func WithConstantField

func WithConstantField(key string, value interface{}) Config

WithConstantField specifies a field name and value that should be included in every log entry before any others (including primary fields).

Example
package main

import (
	"fmt"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gwatts/kvlog"
)

func main() {
	f := kvlog.New(
		kvlog.WithConstantField("commit", "abcd1234"))

	result, _ := f.Format(&log.Entry{
		Time:  time.Date(2017, 1, 2, 12, 0, 0, 0, time.UTC),
		Level: log.InfoLevel,
		Data: log.Fields{
			"msg_count": 1,
		},
	})
	fmt.Println(string(result))

}
Output:
2017-01-02T12:00:00.000Z ll="info" commit="abcd1234" msg_count=1

func WithPrimaryFields

func WithPrimaryFields(field ...string) Config

WithPrimaryFields specifies a number of field names that should always appear first in each log entry (if set). The remaining fields will be sorted into alphabetical order. This can be useful for fields which always appear that need to be seen quickly such as "status" or "action".

type Formatter

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

Formatter emits plain text log lines with k="v" pairs.

func New

func New(cfgs ...Config) *Formatter

New creates a new Formatter.

func (*Formatter) Format

func (cf *Formatter) Format(entry *log.Entry) ([]byte, error)

Format a single log entry into a plain text log line.

type Loggable

type Loggable interface {
	LogValues() map[string]interface{}
}

Loggable is the interface implemented by types that contain multiple k=v values that need to be logged.

Each key in the returned map will be prefixed with the value's key and then merged into the remaining keys for the log entry. Each value will be formatted as any other value (each value may also implement the Marshaler interface, for example).

Example
package main

import (
	"fmt"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gwatts/kvlog"
)

type Timing struct {
	Min    int
	Max    int
	Median int
}

func (t Timing) LogValues() map[string]interface{} {
	return map[string]interface{}{
		".min_ms":    t.Min,
		".max_ms":    t.Max,
		".median_ms": t.Median,
	}
}

func main() {
	t := Timing{
		Min:    5,
		Max:    93,
		Median: 30,
	}

	f := kvlog.New()

	result, _ := f.Format(&log.Entry{
		Time:  time.Date(2017, 1, 2, 12, 0, 0, 0, time.UTC),
		Level: log.InfoLevel,
		Data: log.Fields{
			"exec_times": t,
		},
	})
	fmt.Println(string(result))

}
Output:
2017-01-02T12:00:00.000Z ll="info" exec_times.max_ms=93 exec_times.median_ms=30 exec_times.min_ms=5

type Marshaler

type Marshaler interface {
	MarshalLogValue() string
}

Marshaler is the interface implemented by types that can marshal their own value into a log-friendly format.

Values returned by types implementing this interface do not have newlines stripped, nor are their values quoted; they are included verbatim.

Example
package main

import (
	"fmt"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gwatts/kvlog"
)

type AgeRange struct {
	Youngest int
	Oldest   int
}

func (ar AgeRange) MarshalLogValue() string {
	return fmt.Sprintf(`"%d-%d"`, ar.Youngest, ar.Oldest)
}

func main() {
	ar := AgeRange{
		Youngest: 18,
		Oldest:   93,
	}

	f := kvlog.New()

	result, _ := f.Format(&log.Entry{
		Time:  time.Date(2017, 1, 2, 12, 0, 0, 0, time.UTC),
		Level: log.InfoLevel,
		Data: log.Fields{
			"age_range": ar,
		},
	})
	fmt.Println(string(result))

}
Output:
2017-01-02T12:00:00.000Z ll="info" age_range="18-93"

type RawLogString

type RawLogString string

RawLogString returns a LogValue so that newlines, etc are not stripped and the string is not quoted.

func (RawLogString) MarshalLogValue

func (s RawLogString) MarshalLogValue() string

MarshalLogValue implements the Marshaler interface.

Jump to

Keyboard shortcuts

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