• Stars
    star
    321
  • Rank 130,752 (Top 3 %)
  • Language
    Go
  • License
    BSD 3-Clause "New...
  • Created over 7 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A high-performant Logging Foundation for Go Applications. X3 faster than the rest leveled loggers.

✒️ golog

golog is a zero-dependency simple, fast and easy-to-use level-based logger written in Go Programming Language.

Output from win terminal

build status report card godocs github issues

🚀 Installation

The only requirement is the Go Programming Language*.

Go modules
$ go get github.com/kataras/golog@latest

Or edit your project's go.mod file and execute $ go build.

module your_project_name

go 1.19

require (
    github.com/kataras/golog v0.1.8
)

$ go build

$ go get github.com/kataras/golog@latest
package main

import (
    "github.com/kataras/golog"
)

func main() {
    // Default Output is `os.Stdout`,
    // but you can change it:
    // golog.SetOutput(os.Stderr)

    // Time Format defaults to: "2006/01/02 15:04"
    // you can change it to something else or disable it with:
    // golog.SetTimeFormat("")

    // Level defaults to "info",
    // but you can change it:
    golog.SetLevel("debug")

    golog.Println("This is a raw message, no levels, no colors.")
    golog.Info("This is an info message, with colors (if the output is terminal)")
    golog.Warn("This is a warning message")
    golog.Error("This is an error message")
    golog.Debug("This is a debug message")
    golog.Fatal(`Fatal will exit no matter what,
    but it will also print the log message if logger's Level is >=FatalLevel`)
}

Log Levels

Name Method Text Color
"fatal" Fatal, Fatalf [FTAL] Red background
"error" Error, Errorf [ERRO] Red foreground
"warn" Warn, Warnf, Warningf [WARN] Magenta foreground
"info" Info, Infof [INFO] Cyan foreground
"debug" Debug, Debugf [DBUG] Yellow foreground

On debug level the logger will store stacktrace information to the log instance, which is not printed but can be accessed through a Handler (see below).

Helpers

// GetTextForLevel returns the level's (rich) text. 
fatalRichText := golog.GetTextForLevel(golog.FatalLevel, true)

// fatalRichText == "\x1b[41m[FTAL]\x1b[0m"
// ParseLevel returns a Level based on its string name.
level := golog.ParseLevel("debug")

// level == golog.DebugLevel

Customization

You can customize the log level attributes.

func init() {
    // Levels contains a map of the log levels and their attributes.
    errorAttrs := golog.Levels[golog.ErrorLevel]

    // Change a log level's text.
    customColorCode := 156
    errorAttrs.SetText("custom text", customColorCode)

    // Get (rich) text per log level.
    enableColors := true
    errorRichText := errorAttrs.Text(enableColors)
}

Alternatively, to change a specific text on a known log level, you can just call:

golog.ErrorText("custom text", 156)

Integration

The golog.Logger is using common, expected log methods, therefore you can integrate it with ease.

Take for example the badger database. You want to add a prefix of [badger] in your logs when badger wants to print something.

  1. Create a child logger with a prefix text using the Child function,
  2. disable new lines (because they are managed by badger itself) and you are ready to GO:
opts := badger.DefaultOptions("./data")
opts.Logger = golog.Child("[badger]").DisableNewLine()

db, err := badger.Open(opts)
// [...]

Level-based and standard Loggers

You can put golog in front of your existing loggers using the Install and InstallStd methods.

Any level-based Logger that implements the ExternalLogger can be adapted.

E.g. sirupsen/logrus:

// Simulate a logrus logger preparation.
logrus.SetLevel(logrus.InfoLevel)
logrus.SetFormatter(&logrus.JSONFormatter{})

golog.Install(logrus.StandardLogger())

golog.Debug(`this debug message will not be shown,
    because the logrus level is InfoLevel`)
golog.Error(`this error message will be visible as JSON,
    because of logrus.JSONFormatter`)

Any standard logger (without level capabilities) that implements the StdLogger can be adapted using the InstallStd method.

E.g. log standard package:

// Simulate a log.Logger preparation.
myLogger := log.New(os.Stdout, "", 0)

golog.SetLevel("error")
golog.InstallStd(myLogger)

golog.Error("error message")

Output Format

Any value that completes the Formatter interface can be used to write to the (leveled) output writer. By default the "json" formatter is available.

JSON

import "github.com/kataras/golog"

func main() {
    golog.SetLevel("debug")
    golog.SetFormat("json", "    ") // < --

    // main.go#29
    golog.Debugf("This is a %s with data (debug prints the stacktrace too)", "message", golog.Fields{
        "username": "kataras",
    })
}

Output

{
    "timestamp": 1591423477,
    "level": "debug",
    "message": "This is a message with data (debug prints the stacktrace too)",
    "fields": {
        "username": "kataras"
    },
    "stacktrace": [
        {
            "function": "main.main",
            "source": "C:/example/main.go:29"
        }
    ]
}

Register custom Formatter

golog.RegisterFormatter(new(myFormatter))
golog.SetFormat("myformat", options...)

The Formatter interface looks like this:

// Formatter is responsible to print a log to the logger's writer.
type Formatter interface {
	// The name of the formatter.
	String() string
	// Set any options and return a clone,
	// generic. See `Logger.SetFormat`.
	Options(opts ...interface{}) Formatter
	// Writes the "log" to "dest" logger.
	Format(dest io.Writer, log *Log) bool
}

Custom Format using Handler

The Logger can accept functions to handle (and print) each Log through its Handle method. The Handle method accepts a Handler.

type Handler func(value *Log) (handled bool)

This method can be used to alter Log's fields based on custom logic or to change the output destination and its output format.

Create a JSON handler

import "encoding/json"

func jsonOutput(l *golog.Log) bool {
    enc := json.NewEncoder(l.Logger.GetLevelOutput(l.Level.String()))
    enc.SetIndent("", "    ")
    err := enc.Encode(l)
    return err == nil
}

Register the handler and log something

import "github.com/kataras/golog"

func main() {
    golog.SetLevel("debug")
    golog.Handle(jsonOutput)

    // main.go#29
    golog.Debugf("This is a %s with data (debug prints the stacktrace too)", "message", golog.Fields{
        "username": "kataras",
    })
}

Examples

🔥 Benchmarks

test times ran (large is better) ns/op (small is better) B/op (small is better) allocs/op (small is better)
BenchmarkGologPrint 10000000 3749 ns/op 890 B/op 28 allocs/op
BenchmarkLogrusPrint   3000000 9609 ns/op 1611 B/op 64 allocs/op

Click here for details.

👥 Contributing

If you find that something is not working as expected please open an issue.

More Repositories

1

iris

The fastest HTTP/2 Go Web Framework. New, modern and easy to learn. Fast development with Code you control. Unbeatable cost-performance ratio 🚀
Go
24,911
star
2

neffos

A modern, fast and scalable websocket framework with elegant API written in Go
Go
563
star
3

muxie

Muxie is a modern, fast and light HTTP multiplexer for Go. Fully compatible with the http.Handler interface. Written for everyone.
Go
283
star
4

go-sessions

🔐 The sessions manager for the Go Programming Language. Supports both net/http and fasthttp.
Go
207
star
5

jwt

A fast and simple JWT implementation for Go
Go
194
star
6

rizla

👀 Rizla builds, runs and monitors your Go Applications with ease. See https://github.com/kataras/iris-cli for Iris users.
Go
190
star
7

iris-cli

[WIP] Iris Command Line Interface
Go
118
star
8

i18n

🆕 High-performant and powerful localization and internationalization support for Go
Go
108
star
9

go-events

📣 Pure nodejs EventEmmiter for the Go Programming Language.
Go
96
star
10

server-benchmarks

🚀 Cross-platform transparent benchmarks for HTTP/2 Web Servers at 2020-2024
Go
89
star
11

blocks

Go-idiomatic View Engine
Go
70
star
12

go-websocket

🔈 Deprecated. Use https://github.com/kataras/neffos instead
Go
59
star
13

go-template

🔈 Deprecated. Use https://github.com/kataras/iris/wiki/View instead
Go
56
star
14

versioning

🆕 API Versioning for Go
Go
51
star
15

build-a-better-web-together

Deprecated. Moved to https://github.com/kataras/iris/wiki and https://docs.iris-go.com
CSS
48
star
16

httpcache

ABANDONED: Use https://github.com/kataras/iris instead. Extremely-easy cache service for HTTP/x . Supports both net/http and valyala/fasthttp
Go
43
star
17

neffos.js

Node.js and Browser support for the neffos real-time framework written in Typescript.
TypeScript
39
star
18

hcaptcha

hCaptcha HTTP middleware for Go web servers
Go
32
star
19

pg

PG is a Go library that simplifies PostgreSQL database interaction with struct-based entities, schema management, and repository pattern.
Go
28
star
20

tunnel

Public URLs for exposing your local web server
Go
26
star
21

go-fs

📁 Provides some common utilities which GoLang developers use when working with files, either system files or web files.
Go
26
star
22

rewrite

The rewrite middleware for Go. Perfect for SEO
Go
22
star
23

httpfs

Flexible and easy to use HTTP File Server for Go
Go
20
star
24

pio

Low-level package that provides an easy way to centralize different output targets. Supports colors and text decoration to all popular terminals
Go
20
star
25

sitemap

🆕 Sitemap Protocol for Go | https://support.google.com/webmasters/answer/189077?hl=en
Go
19
star
26

go-errors

⚠️ Better GoLang error handling.
Go
18
star
27

compress

HTTP Compression for Go
Go
16
star
28

go-serializer

➿ Serialize any custom type or convert any content to []byte or string, for Go Programming Language
Go
16
star
29

chronos

NEW: Chronos provides an easy way to limit X operations per Y time in accuracy of nanoseconds
Go
14
star
30

basicauth

The most advanced and powerful Go HTTP Basic Authentication middleware.
Go
13
star
31

gitbook-to-wiki

Export your GitBook as a GitHub Wiki or Docsify pages.
Go
13
star
32

sheets

📊 (Unofficial) A Lightweight Google Spreadsheets Client written in Go
Go
12
star
33

vscode-iris

Iris Web Framework snippets for Visual Studio Code
TypeScript
9
star
34

realip

Extract the real HTTP client's Remote IP Address
Go
8
star
35

methodoverride

🆕 Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it
Go
8
star
36

trie-examples-to-remember-again

A place to keep my coding examples for different kind of trie usage in order to remember them again - this time on github
Go
7
star
37

requestid

Unique Identifier for each HTTP request
Go
6
star
38

go-options

📦 Clean APIs for your Go Applications
Go
5
star
39

httpclient

HTTP/2 Client for Go Programming Language #golang #http
Go
4
star
40

mail

Mail is a ridiculous simple email sender written in Go
Go
4
star
41

pkg

Public Repository of the common packages that Gerasimos Maropoulos, the author of Iris, uses for various commercial or non-commercial projects.
Go
4
star
42

pgx-golog

pgx and golog integration
Go
3
star
43

ultrasecurity

10 seconds post-login OS security
Go
1
star
44

kataras

Gerasimos Maropoulos
1
star