pre

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2024 License: MIT Imports: 12 Imported by: 0

README

Pre

This is a fork of the Logrus Prefixed Formatter which itself is a Logrus formatter mainly based on original logrus.TextFormatter but with a slightly modified colored output and support for custom color themes. We also enable prefixing of log messages using either a field in the log entry called "prefix" or an object called "logging-context" extracted from a context.

Usage

Here is how it should be used:

package main

import (
	log "github.com/sirupsen/logrus"
	"github.com/ljanyst/pre"
)

func init() {
	log.SetFormatter(&pre.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
		FullTimestamp:   true,
		ForceFormatting: true,
	})
	log.SetLevel(log.DebugLevel)
}

func main() {
	log.WithFields(logrus.Fields{
		"prefix": "main",
		"animal": "walrus",
		"number": 8,
	}).Debug("Started observing beach")

	log.WithFields(logrus.Fields{
		"prefix":      "sensor",
		"temperature": -4,
	}).Info("Temperature changes")
}

And here's how it's used with contexts:

package main

import (
	"context"
	"fmt"

	"github.com/ljanyst/pre"
	"github.com/sirupsen/logrus"
)

type TestContext struct {
	Type string
	Foo  string
	Bar  int
}

func (t *TestContext) String() string {
	return fmt.Sprintf("%-5s f: %-10s b: %3d", t.Type, t.Foo, t.Bar)
}

func init() {
	formatter := new(pre.TextFormatter)
	formatter.MinPrefixWidth = 25
	logrus.SetFormatter(formatter)
	logrus.SetLevel(logrus.DebugLevel)
}

func main() {
	logrus.Info("Before context")
	ctx := &TestContext{}
	log := pre.Log(context.WithValue(context.Background(), "logging-context", ctx))
	log.Debugf("Started observing beach")
	ctx.Type = "foo"
	log.Debugf("A group of walrus emerges from the ocean")
	ctx.Foo = "bar"
	log.Warnf("The group's number increased tremendously!")
	ctx.Bar = 42
	log.Infof("Temperature changes")
}

API

pre.TextFormatter exposes the following fields and methods.

Fields
  • ForceColors bool — set to true to bypass checking for a TTY before outputting colors.
  • DisableColors bool — force disabling colors. For a TTY colors are enabled by default.
  • DisableUppercase bool — set to true to turn off the conversion of the log level names to uppercase.
  • ForceFormatting bool — force formatted layout, even for non-TTY output.
  • DisableTimestamp bool — disable timestamp logging. Useful when output is redirected to logging system that already adds timestamps.
  • FullTimestamp bool — enable logging the full timestamp when a TTY is attached instead of just the time passed since beginning of execution.
  • TimestampFormat string — timestamp format to use for display when a full timestamp is printed.
  • DisableSorting bool — the fields are sorted by default for a consistent output. For applications that log extremely frequently and don't use the JSON formatter this may not be desired.
  • QuoteEmptyFields bool — wrap empty fields in quotes if true.
  • QuoteCharacter string — can be set to the override the default quoting character " with something else. For example: ', or `.
  • SpacePadding int — pad msg field with spaces on the right for display. The value for this parameter will be the size of padding. Its default value is zero, which means no padding will be applied.
  • MinPrefixWidth int - the prefixes will be padded to be the length specified by this value. If the value is zero (the default), no padding will be applied.
Methods

SetColorScheme(colorScheme *pre.ColorScheme)

Sets an alternative color scheme for colored output. pre.ColorScheme struct supports the following fields:

  • InfoLevelStyle string — info level style.
  • WarnLevelStyle string — warn level style.
  • ErrorLevelStyle string — error style.
  • FatalLevelStyle string — fatal level style.
  • PanicLevelStyle string — panic level style.
  • DebugLevelStyle string — debug level style.
  • PrefixStyle string — prefix style.
  • TimestampStyle string — timestamp style.

Color styles should be specified using mgutz/ansi style syntax. For example, here is the default theme:

InfoLevelStyle:  "green",
WarnLevelStyle:  "yellow",
ErrorLevelStyle: "red",
FatalLevelStyle: "red",
PanicLevelStyle: "red",
DebugLevelStyle: "blue",
PrefixStyle:     "cyan",
TimestampStyle:  "black+h"

It's not necessary to specify all colors when changing color scheme if you want to change just specific ones:

formatter.SetColorScheme(&pre.ColorScheme{
    PrefixStyle:    "blue+b",
    TimestampStyle: "white+h",
})

pre.Log creates a logrus log wrapper that calls the message functions on log entries created with context:

func (l *LogWrap) Tracef(format string, args ...interface{}) {
	l.log.WithContext(l.ctx).Tracef(format, args...)
}

This removes the need for manually setting the context for every log entry in a given scope.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColorScheme added in v0.4.0

type ColorScheme struct {
	InfoLevelStyle  string
	WarnLevelStyle  string
	ErrorLevelStyle string
	FatalLevelStyle string
	PanicLevelStyle string
	DebugLevelStyle string
	PrefixStyle     string
	TimestampStyle  string
}

type LogWrap added in v0.7.0

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

func Log added in v0.7.0

func Log(ctx context.Context) *LogWrap

func LogCustom added in v0.7.0

func LogCustom(log *logrus.Logger, ctx context.Context) *LogWrap

func (*LogWrap) Debugf added in v0.7.0

func (l *LogWrap) Debugf(format string, args ...interface{})

func (*LogWrap) Errorf added in v0.7.0

func (l *LogWrap) Errorf(format string, args ...interface{})

func (*LogWrap) Fatalf added in v0.7.0

func (l *LogWrap) Fatalf(format string, args ...interface{})

func (*LogWrap) Infof added in v0.7.0

func (l *LogWrap) Infof(format string, args ...interface{})

func (*LogWrap) Panicf added in v0.7.0

func (l *LogWrap) Panicf(format string, args ...interface{})

func (*LogWrap) Printf added in v0.7.0

func (l *LogWrap) Printf(format string, args ...interface{})

func (*LogWrap) Tracef added in v0.7.0

func (l *LogWrap) Tracef(format string, args ...interface{})

func (*LogWrap) Warnf added in v0.7.0

func (l *LogWrap) Warnf(format string, args ...interface{})

func (*LogWrap) Warningf added in v0.7.0

func (l *LogWrap) Warningf(format string, args ...interface{})

type LoggingContext added in v0.7.0

type LoggingContext interface {
	String() string
}

type TextFormatter

type TextFormatter struct {
	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors bool

	// Force disabling colors. For a TTY colors are enabled by default.
	DisableColors bool

	// Force formatted layout, even for non-TTY output.
	ForceFormatting bool

	// Disable timestamp logging. useful when output is redirected to logging
	// system that already adds timestamps.
	DisableTimestamp bool

	// Disable the conversion of the log levels to uppercase
	DisableUppercase bool

	// Enable logging the full timestamp when a TTY is attached instead of just
	// the time passed since beginning of execution.
	FullTimestamp bool

	// Timestamp format to use for display when a full timestamp is printed.
	TimestampFormat string

	// The fields are sorted by default for a consistent output. For applications
	// that log extremely frequently and don't use the JSON formatter this may not
	// be desired.
	DisableSorting bool

	// Wrap empty fields in quotes if true.
	QuoteEmptyFields bool

	// Can be set to the override the default quoting character "
	// with something else. For example: ', or `.
	QuoteCharacter string

	// Pad msg field with spaces on the right for display.
	// The value for this parameter will be the size of padding.
	// Its default value is zero, which means no padding will be applied for msg.
	SpacePadding int

	// The prefixes will be padded to be the length specified by this value.
	MinPrefixWidth int

	sync.Once
	// contains filtered or unexported fields
}

func (*TextFormatter) Format

func (f *TextFormatter) Format(entry *logrus.Entry) ([]byte, error)

func (*TextFormatter) SetColorScheme added in v0.4.0

func (f *TextFormatter) SetColorScheme(colorScheme *ColorScheme)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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