mogrus

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2022 License: MIT Imports: 9 Imported by: 1

README

Errors Logo

made-with-Go Go Report Card Maintainability Test codecov go.dev reference

✏️ Mogrus

A Go wrapper for Logrus, Errors and Mongo giving you extremely detailed log reports. This package is designed to be used with github.com/ainsleyclark/errors for error reporting with codes, messages and more.

Overview

  • ✅ Add hooks to a Mongo collection.
  • ✅ Logs with custom errors featuring codes, messages and lifelines.
  • ✅ Customisable expiry times for different Logrus levels.
  • ✅ Specify a callback function for when an entry is fired to Mongo.

Why?

Detailed and verbose logging is important to any application or API. This package aims to make it easy for APIs to log errors to a central location, using a Logrus Hook.

Installation

go get -u github.com/ainsleyclark/mogrus

How to use

Below is an example of how to use Mogrus, instantiate a Logrus instance and connect to a Mongo DB and pass the hook to the AddHook() function.

Add hook
func ExampleMogrus() {
	l := logrus.New()

	clientOptions := options.Client().
	ApplyURI(os.Getenv("MONGO_CONNECTION")).
	SetServerAPIOptions(options.ServerAPI(options.ServerAPIVersion1))

	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatalln(err)
	}

	opts := mogrus.Options{
		Collection: client.Database("logs").Collection("col"),
		// FireHook is a hook function called just before an
		// entry is logged to Mongo.
		FireHook: func(e mogrus.Entry) {
			fmt.Printf("%+v\n", e)
		},
		// ExpirationLevels allows for the customisation of expiry
		// time for each Logrus level by default entries do not expire.
		ExpirationLevels: mogrus.ExpirationLevels{
			logrus.DebugLevel: time.Second * 5,
			logrus.InfoLevel:  time.Second * 15,
			logrus.ErrorLevel: time.Second * 30,
		},
	}

	// Create the new Mogrus hook, returns an error if the
	// collection is nil.
	hook, err := mogrus.New(context.Background(), opts)
	if err != nil {
		log.Fatalln(err)
	}

	// Add the hook to the Logrus instance.
	l.AddHook(hook)

	l.Debug("Debug level")
	l.WithField("key", "value").Info("Info level")
	l.WithError(errors.NewInternal(errors.New("error"), "message", "op")).Error("Error level")
}
Entry

The definition of an entry below is the object that is fired to Mongo.

// Entry defines a singular entry sent to Mongo
// when a Logrus event is fired.
Entry struct {
	Level   string               `json:"level" bson:"level"`
	Time    time.Time            `json:"time" bson:"time"`
	Message string               `json:"message" bson:"message"`
	Data    map[string]any       `json:"data" bson:"data"`
	Error   *Error               `json:"error" bson:"error"`
	Expiry  map[string]time.Time `json:"expiry" bson:"expiry"`
}
Error

The definition of an error below is the object that is stored in an Entry when log.WithError is used.

// Error defines a custom Error for log entries, detailing
// the file line, errors are returned as strings instead
// of the stdlib error.
Error struct {
	Code      string `json:"code" bson:"code"`
	Message   string `json:"message" bson:"message"`
	Operation string `json:"operation" bson:"op"`
	Err       string `json:"error" bson:"err"`
	FileLine  string `json:"file_line" bson:"file_line"`
}

TODO

  • Add global expiration time for all log levels.
  • Add constructors for:
    • WithDB()
    • WithAuth()
    • New()

Contributing

Please feel free to make a pull request if you think something should be added to this package!

Credits

Shout out to the incredible Maria Letta for her excellent Gopher illustrations.

Licence

Code Copyright 2022 Mogrus. Code released under the MIT Licence.

Documentation

Index

Constants

View Source
const (
	// DefaultExpiryKey is the key and index stored within
	// Mongo for log levels that have a duration.
	DefaultExpiryKey = "ttl-%s"
)

Variables

This section is empty.

Functions

func New

func New(ctx context.Context, opts Options) (logrus.Hook, error)

New creates a new Mogrus hooker. Returns errors.INVALID if the collection is nil. Returns errors.INTERNAL if the indexes could not be added.

Types

type Entry

type Entry struct {
	ID      primitive.ObjectID   `json:"id,omitempty" bson:"_id,omitempty"`
	Level   string               `json:"level" bson:"level"`
	Time    time.Time            `json:"time" bson:"time"`
	Message string               `json:"message" bson:"message"`
	Data    map[string]any       `json:"data" bson:"data"`
	Error   *Error               `json:"error" bson:"error"`
	Expiry  map[string]time.Time `json:"expiry" bson:"expiry"`
}

Entry defines a singular entry sent to Mongo when a Logrus event is fired.

func ToEntry added in v0.0.3

func ToEntry(entry *logrus.Entry) Entry

ToEntry transforms a logrus.Entry to a mogrus.Entry

func (*Entry) HasError

func (e *Entry) HasError() bool

HasError returns true if the Entry has an error attached to it.

type Error

type Error struct {
	Code      string `json:"code" bson:"code"`
	Message   string `json:"message" bson:"message"`
	Operation string `json:"operation" bson:"op"`
	Err       string `json:"error" bson:"err"`
	FileLine  string `json:"file_line" bson:"file_line"`
}

Error defines a custom Error for log entries, detailing the file line, errors are returned as strings instead of the stdlib error.

func (*Error) Error

func (e *Error) Error() error

Error implements the stdlib error interface.

type ExpirationLevels

type ExpirationLevels map[logrus.Level]time.Duration

ExpirationLevels defines the map of log levels mapped to a duration a LevelIndex.

type FireHook

type FireHook func(e Entry)

FireHook defines the function used for firing entry to a call back function.

type Options

type Options struct {
	// Collection is the Mongo collection to write to when
	// a log is fired.
	Collection *mongo.Collection
	// FireHook is a hook function called just before an
	// entry is logged to Mongo.
	FireHook FireHook
	// ExpirationLevels allows for the customisation of expiry
	// time for each Logrus level by default entries do not expire.
	// There may be instances where you want to keep Panics in
	// the Mongo collection for longer than trace levels.
	// For example:
	/*
		var levels = ExpirationLevels{
			// Expire trace levels after 10 hours.
			logrus.TraceLevel: time.Hour * 10
			// Expire info levels after 24 hours.
			logrus.InfoLevel:t ime.Hour * 24,
			// Expire panic levels after 1 week.
			logrus.InfoLevel:t ime.Hour * 24 * 6,
		}
	*/
	ExpirationLevels ExpirationLevels
}

Options defines the configuration used for creating a new Mogrus hook.

func (Options) Validate

func (o Options) Validate() error

Validate validates the options before creating a new Hook.

Jump to

Keyboard shortcuts

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