golog

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: BSD-3-Clause Imports: 13 Imported by: 1,327

README ΒΆ

βœ’οΈ 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.22

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

$ 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`)

    // Use any other supported logger through golog, e.g. the new "log/slog":
    // golog.Install(slog.Default())
}

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 method.

Supporte loggers:

  • log
  • slog
  • logrus

Example for log/slog standard package:

// Simulate an slog.Logger preparation.
var myLogger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelDebug,
}))

func main() {
    golog.SetLevel("error")
    golog.Install(myLogger)

    golog.Error("error message")
}

Example for log standard package:

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

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

golog.Error("error message")

Example for 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`)

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.

Documentation ΒΆ

Overview ΒΆ

CBSD 3-Clause License

Copyright (c) 2017-2022, Gerasimos (Makis) Maropoulos (kataras2006@hotmail.com) All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/* Package golog provides an easy to use foundation for your logging operations.

Source code and other details for the project are available at GitHub:

https://github.com/kataras/golog

Current Version ΒΆ

0.1.12

Installation ΒΆ

The only requirement is the Go Programming Language

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

Overview ΒΆ

Example code:

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")
}

New ΒΆ

Golog has a default, package-level initialized instance for you, however you can choose to create and use a logger instance for a specific part of your application.

Example Code:

package main

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

func main() {
	log := golog.New()

	// Default Output is `os.Stdout`,
	// but you can change it:
	// log.SetOutput(os.Stderr)

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

	log.Println("This is a raw message, no levels, no colors.")
	log.Info("This is an info message, with colors (if the output is terminal)")
	log.Warn("This is a warning message")
	log.Error("This is an error message")
	log.Debug("This is a debug message")
}

Format ΒΆ

Golog sets colors to levels when its `Printer.Output` is actual a compatible terminal which can renders colors, otherwise it will downgrade itself to a white foreground.

Golog has functions to print a formatted log too.

Example Code:

golog.Infof("[%d] This is an info %s", 1, "formatted log")
golog.Warnf("[%d] This is an info %s", 1, "formatted log")
golog.Errorf("[%d] This is an info %s", 1, "formatted log")
golog.Debugf("[%d] This is an info %s", 1, "formatted log")

Output ΒΆ

Golog takes a simple `io.Writer` as its underline Printer's Output.

Example Code:

golog.SetOutput(io.Writer)

You can even override the default line braker, "\n", by using the `golog#NewLine` function at startup.

Example Code:

golog.NewLine("\r\n")

Levels ΒΆ

Golog is a leveled logger, therefore you can set a level and print whenever the print level is valid with the set-ed one.

Available built'n levels are:

// DisableLevel will disable printer
DisableLevel Level = iota
// ErrorLevel will print only errors
ErrorLevel
// WarnLevel will print errors and warnings
WarnLevel
// InfoLevel will print errors, warnings and infos
InfoLevel
// DebugLevel will print on any level, errors, warnings, infos and debug messages
DebugLevel

Below you'll learn a way to add a custom level or modify an existing level.

The default colorful text(or raw text for unsupported outputs) for levels can be overridden by using the `golog#ErrorText, golog#WarnText, golog#InfoText and golog#DebugText` functions.

Example Code:

package main

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

func main() {

	// First argument is the raw text for outputs
	// second argument is the color code
	// and the last, variadic argument can be any `kataras/pio.RichOption`, e.g. pio.Background, pio.Underline.

	// Default is "[ERRO]"
	golog.ErrorText("|ERROR|", 31)
	// Default is "[WARN]"
	golog.WarnText("|WARN|", 32)
	// Default is "[INFO]"
	golog.InfoText("|INFO|", 34)
	// Default is "[DBUG]"
	golog.DebugText("|DEBUG|", 33)

	// Business as usual...
	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 gives you the power to add or modify existing levels is via Level Metadata.

Example Code:

package main

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

func main() {
	// Let's add a custom level,
	//
	// It should be starting from level index 6,
	// because we have 6 built'n levels  (0 is the start index):
	// disable,
	// fatal,
	// error,
	// warn,
	// info
	// debug

	// First we create our level to a golog.Level
	// in order to be used in the Log functions.
	var SuccessLevel golog.Level = 6
	// Register our level, just three fields.
	golog.Levels[SuccessLevel] = &golog.LevelMetadata{
		Name:      "success",
		Title:     "[SUCC]",
		ColorCode: 32, // Green
	}

	// create a new golog logger
	myLogger := golog.New()

	// set its level to the higher in order to see it
	// ("success" is the name we gave to our level)
	myLogger.SetLevel("success")

	// and finally print a log message with our custom level
	myLogger.Logf(SuccessLevel, "This is a success log message with green color")
}

The logger's level can be changed via passing one of the level constants to the `Level` field or by passing its string representation to the `SetLevel` function.

Example Code:

golog.SetLevel("disable")
golog.SetLevel("fatal")
golog.SetLevel("error")
golog.SetLevel("warn")
golog.SetLevel("info")
golog.SetLevel("debug")

Integrations ΒΆ

Transaction with your favorite, but deprecated logger is easy. Golog offers two basic interfaces, the `ExternalLogger` and the `StdLogger` that can be directly used as arguments to the `Install` function in order to adapt an external logger.

Outline:

// Install receives  an external logger
// and automatically adapts its print functions.
//
// Install adds a golog handler to support third-party integrations,
// it can be used only once per `golog#Logger` instance.
//
// For example, if you want to print using a logrus
// logger you can do the following:
//
//	Install(logrus.StandardLogger())
//
// Or the standard log's Logger:
//
//	import "log"
//	myLogger := log.New(os.Stdout, "", 0)
//	Install(myLogger)
//
// Or even the slog/log's Logger:
//
//	import "log/slog"
//	myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
//	Install(myLogger) OR Install(slog.Default())
//
// Look `golog#Logger.Handle` for more.
Install(logger ExternalLogger)

Logrus Integration ΒΆ

Example Code:

package main

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

func main() {
	// outputOnly()
	full()
}

func full() {
	// simulate a logrus preparation:
	logrus.SetLevel(logrus.InfoLevel)
	logrus.SetFormatter(&logrus.JSONFormatter{})

	// pass logrus.StandardLogger() to print logs using using the default,
	// package-level logrus' instance of Logger:
	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")

	// simulate a change of the logrus formatter
	// as you see we have nothing more to change
	// on the golog, it works out of the box,
	// it will be adapt by this change, automatically.
	logrus.SetFormatter(&logrus.TextFormatter{})

	golog.Error("this error message will be visible as text")
	golog.Info("this info message will be visible as text")
}

func outputOnly() {
	golog.SetOutput(logrus.StandardLogger().Out)
	golog.Info(`output only, this will print the same contents
	as golog but using the defined logrus' io.Writer`)

	golog.Error("this error message will be visible as text")
}

Standard `log.Logger` Integration ΒΆ

Example Code:

package main

import (
	"log"
	"os"

	"github.com/kataras/golog"
)

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

func main() {
	golog.SetLevel("error")
	golog.Install(myLogger)

	golog.Debug(`this debug message will not be shown,
	because the golog level is ErrorLevel`)

	golog.Error("this error message will be visible the only visible")

	golog.Warn("this info message will not be visible")
}

That's the basics ΒΆ

But you should have a basic idea of the golog package by now, we just scratched the surface. If you enjoy what you just saw and want to learn more, please follow the below links:

Examples:

https://github.com/kataras/golog/tree/master/_examples

Index ΒΆ

Constants ΒΆ

View Source
const Version = "0.1.12"

Version is the version string representation of the "golog" package.

Variables ΒΆ

View Source
var (
	// ErrorText can modify the prefix that will be prepended
	// to the output message log when `Error/Errorf` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[ERRO]" and pio.Red("[ERRO]").
	//
	// Deprecated Use `Levels[ErrorLevel].SetText(string, string)` instead.
	ErrorText = Levels[ErrorLevel].SetText

	// WarnText can modify the prefix that will be prepended
	// to the output message log when `Warn/Warnf` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[WARN]" and pio.Purple("[WARN]").
	//
	// Deprecated Use `Levels[WarnLevel].SetText(string, string)` instead.
	WarnText = Levels[WarnLevel].SetText

	// InfoText can modify the prefix that will be prepended
	// to the output message log when `Info/Infof` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[INFO]" and pio.LightGreen("[INFO]").
	//
	// Deprecated Use `Levels[InfoLevel].SetText(string, string)` instead.
	InfoText = Levels[InfoLevel].SetText

	// DebugText can modify the prefix that will be prepended
	// to the output message log when `Info/Infof` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[DBUG]" and pio.Yellow("[DBUG]").
	//
	// Deprecated Use `Levels[DebugLevel].SetText(string, string)` instead.
	DebugText = Levels[DebugLevel].SetText

	// GetTextForLevel is the function which
	// has the "final" responsibility to generate the text (colorful or not)
	// that is prepended to the leveled log message
	// when `Error/Errorf, Warn/Warnf, Info/Infof or Debug/Debugf`
	// functions are being called.
	//
	// It can be used to override the default behavior, at the start-up state.
	GetTextForLevel = func(level Level, enableColor bool) string {
		if meta, ok := Levels[level]; ok {
			return meta.Text(enableColor)
		}
		return ""
	}

	// GetNameForLevel is the function which
	// has the "final" responsibility to generagte the name of the level
	// that is prepended to the leveled log message
	GetNameForLevel = func(level Level) string {
		if meta, ok := Levels[level]; ok {
			return meta.Name
		}
		return ""
	}
)
View Source
var Default = New()

Default is the package-level ready-to-use logger, level had set to "info", is changeable.

View Source
var Levels = map[Level]*LevelMetadata{
	DisableLevel: {
		Name:             "disable",
		AlternativeNames: []string{"disabled"},
		Title:            "",
	},
	FatalLevel: {
		Name:      "fatal",
		Title:     "[FTAL]",
		ColorCode: pio.Red,
		Style:     []pio.RichOption{pio.Background},
	},
	ErrorLevel: {
		Name:      "error",
		Title:     "[ERRO]",
		ColorCode: pio.Red,
	},
	WarnLevel: {
		Name:             "warn",
		AlternativeNames: []string{"warning"},
		Title:            "[WARN]",
		ColorCode:        pio.Magenta,
	},
	InfoLevel: {
		Name:      "info",
		Title:     "[INFO]",
		ColorCode: pio.Cyan,
	},
	DebugLevel: {
		Name:      "debug",
		Title:     "[DBUG]",
		ColorCode: pio.Yellow,
	},
}

Levels contains the levels and their mapped (pointer of, in order to be able to be modified) metadata, callers are allowed to modify this package-level global variable without any loses.

View Source
var NopOutput = pio.NopOutput()

NopOutput disables the output.

View Source
var Now func() time.Time = time.Now

Now is called to set the log's timestamp value. It can be altered through initialization of the program to customize the behavior of getting the current time.

Functions ΒΆ

func AddOutput ΒΆ

func AddOutput(writers ...io.Writer)

AddOutput adds one or more `io.Writer` to the Default Logger's Printer.

If one of the "writers" is not a terminal-based (i.e File) then colors will be disabled for all outputs.

func Debug ΒΆ

func Debug(v ...interface{})

Debug will print when logger's Level is debug.

func Debugf ΒΆ

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

Debugf will print when logger's Level is debug.

func Error ΒΆ

func Error(v ...interface{})

Error will print only when logger's Level is error, warn, info or debug.

func Errorf ΒΆ

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

Errorf will print only when logger's Level is error, warn, info or debug.

func Fatal ΒΆ

func Fatal(v ...interface{})

Fatal `os.Exit(1)` exit no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.

func Fatalf ΒΆ

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

Fatalf will `os.Exit(1)` no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.

func GetLevelOutput ΒΆ added in v0.1.4

func GetLevelOutput(levelName string) io.Writer

GetLevelOutput returns the responsible writer for the given "levelName". If not a registered writer is set for that level then it returns the logger's default printer. It does NOT return nil.

func Handle ΒΆ

func Handle(handler Handler)

Handle adds a log handler to the default logger.

Handlers can be used to intercept the message between a log value and the actual print operation, it's called when one of the print functions called. If it's return value is true then it means that the specific handler handled the log by itself therefore no need to proceed with the default behavior of printing the log to the specified logger's output.

It stops on the handler which returns true firstly. The `Log` value holds the level of the print operation as well.

func Hijack ΒΆ

func Hijack(hijacker func(ctx *pio.Ctx))

Hijack adds a hijacker to the low-level logger's Printer. If you need to implement such as a low-level hijacker manually, then you have to make use of the pio library.

func Info ΒΆ

func Info(v ...interface{})

Info will print when logger's Level is info or debug.

func Infof ΒΆ

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

Infof will print when logger's Level is info or debug.

func Install ΒΆ

func Install(logger any)

Install receives an external logger and automatically adapts its print functions.

Install adds a golog handler to support third-party integrations, it can be used only once per `golog#Logger` instance.

For example, if you want to print using a logrus logger you can do the following:

Install(logrus.StandardLogger())

Or the standard log's Logger:

import "log"
myLogger := log.New(os.Stdout, "", 0)
Install(myLogger)

Or even the slog/log's Logger:

import "log/slog"
myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
Install(myLogger) OR Install(slog.Default())

Look `golog#Logger.Handle` for more.

func Logf ΒΆ

func Logf(level Level, format string, args ...interface{})

Logf prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.

func NewLine ΒΆ

func NewLine(newLineChar string)

NewLine can override the default package-level line breaker, "\n". It should be called (in-sync) before the print or leveled functions.

See `github.com/kataras/pio#NewLine` and `Logger#NewLine` too.

func Print ΒΆ

func Print(v ...interface{})

Print prints a log message without levels and colors.

func Println ΒΆ

func Println(v ...interface{})

Println prints a log message without levels and colors. It adds a new line at the end.

func Reset ΒΆ

func Reset()

Reset re-sets the default logger to an empty one.

func Scan ΒΆ

func Scan(r io.Reader) (cancel func())

Scan scans everything from "r" and prints its new contents to the logger's Printer's Output, forever or until the returning "cancel" is fired, once.

func SetLevel ΒΆ

func SetLevel(levelName string)

SetLevel accepts a string representation of a `Level` and returns a `Level` value based on that "levelName".

Available level names are: "disable" "fatal" "error" "warn" "info" "debug"

Alternatively you can use the exported `Default.Level` field, i.e `Default.Level = golog.ErrorLevel`

func SetOutput ΒΆ

func SetOutput(w io.Writer)

SetOutput overrides the Default Logger's Printer's output with another `io.Writer`.

func Warn ΒΆ

func Warn(v ...interface{})

Warn will print when logger's Level is warn, info or debug.

func Warnf ΒΆ

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

Warnf will print when logger's Level is warn, info or debug.

Types ΒΆ

type ExternalLogger ΒΆ

type ExternalLogger interface {
	Print(...interface{})
	Println(...interface{})
	Error(...interface{})
	Warn(...interface{})
	Info(...interface{})
	Debug(...interface{})
}

ExternalLogger is a typical logger interface. Any logger or printer that completes this interface can be used to intercept and handle the golog's messages.

See `Logger#Install` and `Logger#Handle` for more.

type Fields ΒΆ added in v0.0.16

type Fields map[string]interface{}

Fields is a map type. One or more values of `Fields` type can be passed on all Log methods except `Print/Printf/Println` to set the `Log.Fields` field, which can be accessed through a custom LogHandler.

type Formatter ΒΆ added in v0.1.5

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
}

Formatter is responsible to print a log to the logger's writer.

type Frame ΒΆ added in v0.0.16

type Frame struct {
	// Function is the package path-qualified function name of
	// this call frame. If non-empty, this string uniquely
	// identifies a single function in the program.
	// This may be the empty string if not known.
	Function string `json:"function"`
	// Source contains the file name and line number of the
	// location in this frame. For non-leaf frames, this will be
	// the location of a call.
	Source string `json:"source"`
}

Frame represents the log's caller.

func GetStacktrace ΒΆ added in v0.0.16

func GetStacktrace(limit int) (callerFrames []Frame)

GetStacktrace tries to return the callers of this function.

func (Frame) String ΒΆ added in v0.0.16

func (f Frame) String() string

String method returns the concat value of "file:line". Implements the `fmt.Stringer` interface.

type Handler ΒΆ

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

Handler is the signature type for logger's handler.

A Handler can be used to intercept the message between a log value and the actual print operation, it's called when one of the print functions called. If it's return value is true then it means that the specific handler handled the log by itself therefore no need to proceed with the default behavior of printing the log to the specified logger's output.

It stops on the handler which returns true firstly. The `Log` value holds the level of the print operation as well.

type JSONFormatter ΒΆ added in v0.1.5

type JSONFormatter struct {
	Indent string
	// contains filtered or unexported fields
}

JSONFormatter is a Formatter type for JSON logs.

func (*JSONFormatter) Format ΒΆ added in v0.1.5

func (f *JSONFormatter) Format(dest io.Writer, log *Log) bool

Format prints the logs in JSON format.

Usage: logger.SetFormat("json") or logger.SetLevelFormat("info", "json")

func (*JSONFormatter) Options ΒΆ added in v0.1.5

func (f *JSONFormatter) Options(opts ...interface{}) Formatter

Options sets the options for the JSON Formatter (currently only indent).

func (*JSONFormatter) String ΒΆ added in v0.1.5

func (f *JSONFormatter) String() string

String returns the name of the Formatter. In this case it returns "json". It's used to map the formatter names with their implementations.

type Level ΒΆ

type Level uint32

Level is a number which defines the log level.

const (
	// DisableLevel will disable the printer.
	DisableLevel Level = iota
	// FatalLevel will `os.Exit(1)` no matter the level of the logger.
	// If the logger's level is fatal, error, warn, info or debug
	// then it will print the log message too.
	FatalLevel
	// ErrorLevel will print only errors.
	ErrorLevel
	// WarnLevel will print errors and warnings.
	WarnLevel
	// InfoLevel will print errors, warnings and infos.
	InfoLevel
	// DebugLevel will print on any level, fatals, errors, warnings, infos and debug logs.
	DebugLevel
)

The available built'n log levels, users can add or modify a level via `Levels` field.

func ParseLevel ΒΆ

func ParseLevel(levelName string) Level

ParseLevel returns a `golog.Level` from a string level. Note that all existing log levels (name, prefix and color) can be customized and new one can be added by the package-level `golog.Levels` map variable.

func (Level) MarshalJSON ΒΆ added in v0.0.16

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON implements the json marshaler for Level.

func (Level) String ΒΆ added in v0.1.4

func (l Level) String() string

String implements the fmt.Stringer interface for level. Returns the level's name.

type LevelMetadata ΒΆ

type LevelMetadata struct {
	// The Name of the Level
	// that named (lowercased) will be used
	// to convert a string level on `SetLevel`
	// to the correct Level type.
	Name string
	// AlternativeNames are the names that can be referred to this specific log level.
	// i.e Name = "warn"
	// AlternativeNames = []string{"warning"}, it's an optional field,
	// therefore we keep Name as a simple string and created this new field.
	AlternativeNames []string
	// Tha Title is the prefix of the log level.
	// See `ColorCode` and `Style` too.
	// Both `ColorCode` and `Style` should be respected across writers.
	Title string
	// ColorCode a color for the `Title`.
	ColorCode int
	// Style one or more rich options for the `Title`.
	Style []pio.RichOption
}

LevelMetadata describes the information behind a log Level, each level has its own unique metadata.

func (*LevelMetadata) SetText ΒΆ

func (m *LevelMetadata) SetText(title string, colorCode int, style ...pio.RichOption)

SetText can modify the prefix that will be prepended to the output message log when `Error/Errorf` functions are being used.

func (*LevelMetadata) Text ΒΆ

func (m *LevelMetadata) Text(enableColor bool) string

Text returns the text that should be prepended to the log message when a specific log level is being written.

type Log ΒΆ

type Log struct {
	// Logger is the original printer of this Log.
	Logger *Logger `json:"-"`
	// Time is the time of fired.
	Time time.Time `json:"-"`
	// Timestamp is the unix time in second of fired.
	Timestamp int64 `json:"timestamp,omitempty"`
	// Level is the log level.
	Level Level `json:"level"`
	// Message is the string reprensetation of the log's main body.
	Message string `json:"message"`
	// Fields any data information useful to represent this log.
	Fields Fields `json:"fields,omitempty"`
	// Stacktrace contains the stack callers when on `Debug` level.
	// The first one should be the Logger's direct caller function.
	Stacktrace []Frame `json:"stacktrace,omitempty"`
	// NewLine returns false if this Log
	// derives from a `Print` function,
	// otherwise true if derives from a `Println`, `Error`, `Errorf`, `Warn`, etc...
	//
	// This NewLine does not mean that `Message` ends with "\n" (or `pio#NewLine`).
	// NewLine has to do with the methods called,
	// not the original content of the `Message`.
	NewLine bool `json:"-"`
}

A Log represents a log line.

func (*Log) FormatTime ΒΆ

func (l *Log) FormatTime() string

FormatTime returns the formatted `Time`.

type Logger ΒΆ

type Logger struct {
	Prefix     string
	Level      Level
	TimeFormat string
	// Limit stacktrace entries on `Debug` level.
	StacktraceLimit int
	// if new line should be added on all log functions, even the `F`s.
	// It defaults to true.
	//
	// See `golog#NewLine(newLineChar string)` as well.
	//
	// Note that this will not override the time and level prefix,
	// if you want to customize the log message please read the examples
	// or navigate to: https://github.com/kataras/golog/issues/3#issuecomment-355895870.
	NewLine bool

	Printer *pio.Printer
	// The per log level raw writers, optionally.
	LevelOutput map[Level]io.Writer

	LevelFormatter map[Level]Formatter // per level formatter.
	// contains filtered or unexported fields
}

Logger is our golog.

func Child ΒΆ

func Child(key interface{}) *Logger

Child (creates if not exists and) returns a new child Logger based on the current logger's fields.

Can be used to separate logs by category. If the "key" is string then it's used as prefix, which is appended to the current prefix one.

func LastChild ΒΆ added in v0.1.3

func LastChild() *Logger

LastChild returns the last registered child Logger.

func New ΒΆ

func New() *Logger

New returns a new golog with a default output to `os.Stdout` and level to `InfoLevel`.

func RegisterFormatter ΒΆ added in v0.1.5

func RegisterFormatter(f Formatter) *Logger

RegisterFormatter registers a Formatter for this logger.

func SetChildPrefix ΒΆ added in v0.1.1

func SetChildPrefix(s string) *Logger

SetChildPrefix same as `SetPrefix` but it does NOT override the existing, instead the given "s" is appended to the current one. It's useful to chian loggers with their own names/prefixes. It does add the ": " in the end of "s" if it's missing. It returns itself.

func SetFormat ΒΆ added in v0.1.5

func SetFormat(formatter string, opts ...interface{}) *Logger

SetFormat sets a default formatter for all log levels.

func SetLevelFormat ΒΆ added in v0.1.5

func SetLevelFormat(levelName string, formatter string, opts ...interface{}) *Logger

SetLevelFormat changes the output format for the given "levelName".

func SetLevelOutput ΒΆ added in v0.1.3

func SetLevelOutput(levelName string, w io.Writer) *Logger

SetLevelOutput sets a destination log output for the specific "levelName". For multiple writers use the `io.Multiwriter` wrapper.

func SetPrefix ΒΆ

func SetPrefix(s string) *Logger

SetPrefix sets a prefix for the default package-level Logger.

The prefix is the first space-separated word that is being presented to the output. It's written even before the log level text.

Returns itself.

func SetStacktraceLimit ΒΆ added in v0.0.17

func SetStacktraceLimit(limit int) *Logger

SetStacktraceLimit sets a stacktrace entries limit on `Debug` level. Zero means all number of stack entries will be logged. Negative value disables the stacktrace field.

func SetTimeFormat ΒΆ

func SetTimeFormat(s string) *Logger

SetTimeFormat sets time format for logs, if "s" is empty then time representation will be off.

func (*Logger) AddOutput ΒΆ

func (l *Logger) AddOutput(writers ...io.Writer) *Logger

AddOutput adds one or more `io.Writer` to the Logger's Printer.

If one of the "writers" is not a terminal-based (i.e File) then colors will be disabled for all outputs.

Returns itself.

func (*Logger) Child ΒΆ

func (l *Logger) Child(key interface{}) *Logger

Child (creates if not exists and) returns a new child Logger based on the current logger's fields.

Can be used to separate logs by category. If the "key" is string then it's used as prefix, which is appended to the current prefix one.

func (*Logger) Clone ΒΆ

func (l *Logger) Clone() *Logger

Clone returns a copy of this "l" Logger. This copy is returned as pointer as well.

func (*Logger) Debug ΒΆ

func (l *Logger) Debug(v ...interface{})

Debug will print when logger's Level is debug.

func (*Logger) Debugf ΒΆ

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

Debugf will print when logger's Level is debug.

func (*Logger) DisableNewLine ΒΆ

func (l *Logger) DisableNewLine() *Logger

DisableNewLine disables the new line suffix on every log function, even the `F`'s, the caller should add "\n" to the log message manually after this call.

Returns itself.

func (*Logger) Error ΒΆ

func (l *Logger) Error(v ...interface{})

Error will print only when logger's Level is error, warn, info or debug.

func (*Logger) Errorf ΒΆ

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

Errorf will print only when logger's Level is error, warn, info or debug.

func (*Logger) Fatal ΒΆ

func (l *Logger) Fatal(v ...interface{})

Fatal `os.Exit(1)` exit no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.

func (*Logger) Fatalf ΒΆ

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

Fatalf will `os.Exit(1)` no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.

func (*Logger) GetLevelOutput ΒΆ added in v0.1.4

func (l *Logger) GetLevelOutput(levelName string) io.Writer

GetLevelOutput returns the responsible writer for the given "levelName". If not a registered writer is set for that level then it returns the logger's default printer. It does NOT return nil.

func (*Logger) Handle ΒΆ

func (l *Logger) Handle(handler Handler)

Handle adds a log handler.

Handlers can be used to intercept the message between a log value and the actual print operation, it's called when one of the print functions called. If it's return value is true then it means that the specific handler handled the log by itself therefore no need to proceed with the default behavior of printing the log to the specified logger's output.

It stops on the handler which returns true firstly. The `Log` value holds the level of the print operation as well.

func (*Logger) Hijack ΒΆ

func (l *Logger) Hijack(hijacker func(ctx *pio.Ctx))

Hijack adds a hijacker to the low-level logger's Printer. If you need to implement such as a low-level hijacker manually, then you have to make use of the pio library.

func (*Logger) Info ΒΆ

func (l *Logger) Info(v ...interface{})

Info will print when logger's Level is info or debug.

func (*Logger) Infof ΒΆ

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

Infof will print when logger's Level is info or debug.

func (*Logger) Install ΒΆ

func (l *Logger) Install(logger any)

Install receives an external logger and automatically adapts its print functions.

Install adds a golog handler to support third-party integrations, it can be used only once per `golog#Logger` instance.

For example, if you want to print using a logrus logger you can do the following:

Install(logrus.StandardLogger())

Or the standard log's Logger:

import "log"
myLogger := log.New(os.Stdout, "", 0)
Install(myLogger)

Or even the slog/log's Logger:

import "log/slog"
myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
Install(myLogger) OR Install(slog.Default())

Look `golog#Logger.Handle` for more.

func (*Logger) LastChild ΒΆ added in v0.1.3

func (l *Logger) LastChild() *Logger

LastChild returns the last registered child Logger.

func (*Logger) Log ΒΆ

func (l *Logger) Log(level Level, v ...interface{})

Log prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.

func (*Logger) Logf ΒΆ

func (l *Logger) Logf(level Level, format string, args ...interface{})

Logf prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.

func (*Logger) Print ΒΆ

func (l *Logger) Print(v ...interface{})

Print prints a log message without levels and colors.

func (*Logger) Printf ΒΆ

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

Printf formats according to a format specifier and writes to `Printer#Output` without levels and colors.

func (*Logger) Println ΒΆ

func (l *Logger) Println(v ...interface{})

Println prints a log message without levels and colors. It adds a new line at the end, it overrides the `NewLine` option.

func (*Logger) RegisterFormatter ΒΆ added in v0.1.5

func (l *Logger) RegisterFormatter(f Formatter) *Logger

RegisterFormatter registers a Formatter for this logger.

func (*Logger) Scan ΒΆ

func (l *Logger) Scan(r io.Reader) (cancel func())

Scan scans everything from "r" and prints its new contents to the logger's Printer's Output, forever or until the returning "cancel" is fired, once.

func (*Logger) SetChildPrefix ΒΆ added in v0.1.1

func (l *Logger) SetChildPrefix(prefix string) *Logger

SetChildPrefix same as `SetPrefix` but it does NOT override the existing, instead the given "prefix" is appended to the current one. It's useful to chian loggers with their own names/prefixes. It does add the ": " in the end of "prefix" if it's missing. It returns itself.

func (*Logger) SetFormat ΒΆ added in v0.1.5

func (l *Logger) SetFormat(formatter string, opts ...interface{}) *Logger

SetFormat sets a formatter for all logger's logs.

func (*Logger) SetLevel ΒΆ

func (l *Logger) SetLevel(levelName string) *Logger

SetLevel accepts a string representation of a `Level` and returns a `Level` value based on that "levelName".

Available level names are: "disable" "fatal" "error" "warn" "info" "debug"

Alternatively you can use the exported `Level` field, i.e `Level = golog.ErrorLevel`

Returns itself.

func (*Logger) SetLevelFormat ΒΆ added in v0.1.5

func (l *Logger) SetLevelFormat(levelName string, formatter string, opts ...interface{}) *Logger

SetLevelFormat changes the output format for the given "levelName".

func (*Logger) SetLevelOutput ΒΆ added in v0.1.3

func (l *Logger) SetLevelOutput(levelName string, w io.Writer) *Logger

SetLevelOutput sets a destination log output for the specific "levelName". For multiple writers use the `io.Multiwriter` wrapper.

func (*Logger) SetOutput ΒΆ

func (l *Logger) SetOutput(w io.Writer) *Logger

SetOutput overrides the Logger's Printer's Output with another `io.Writer`.

Returns itself.

func (*Logger) SetPrefix ΒΆ

func (l *Logger) SetPrefix(s string) *Logger

SetPrefix sets a prefix for this "l" Logger.

The prefix is the text that is being presented to the output right before the log's message.

Returns itself.

func (*Logger) SetStacktraceLimit ΒΆ added in v0.0.17

func (l *Logger) SetStacktraceLimit(limit int) *Logger

SetStacktraceLimit sets a stacktrace entries limit on `Debug` level. Zero means all number of stack entries will be logged. Negative value disables the stacktrace field.

func (*Logger) SetTimeFormat ΒΆ

func (l *Logger) SetTimeFormat(s string) *Logger

SetTimeFormat sets time format for logs, if "s" is empty then time representation will be off.

Returns itself.

func (*Logger) Warn ΒΆ

func (l *Logger) Warn(v ...interface{})

Warn will print when logger's Level is warn, info or debug.

func (*Logger) Warnf ΒΆ

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

Warnf will print when logger's Level is warn, info or debug.

func (*Logger) Warningf ΒΆ added in v0.0.14

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

Warningf exactly the same as `Warnf`. It's here for badger integration: https://github.com/dgraph-io/badger/blob/ef28ef36b5923f12ffe3a1702bdfa6b479db6637/logger.go#L25

type StdLogger ΒΆ

type StdLogger interface {
	Printf(format string, v ...interface{})
	Print(v ...interface{})
	Println(v ...interface{})
}

StdLogger is the standard log.Logger interface. Any logger or printer that completes this interface can be used to intercept and handle the golog's messages.

See `Logger#Install` and `Logger#Handle` for more.

Directories ΒΆ

Path Synopsis
_examples
level-output
Package main shows how you can register a log output per level.
Package main shows how you can register a log output per level.

Jump to

Keyboard shortcuts

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