Giter Club home page Giter Club logo

mogrus's Introduction

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.

mogrus's People

Contributors

ainsleyclark avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mogrus's Issues

Add _id

Add ID to Log Entry

ID  primitive.ObjectID `bson:"_id,omitempty"`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.