golog

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2019 License: BSD-3-Clause Imports: 7 Imported by: 0

README ΒΆ

βœ’οΈ golog

golog is a simple, fast and easy-to-use level-based logger written entirely in GoLang.

Output from win terminal

build status report card godocs github issues

πŸ₯‡ Features
  • Focus on high performance and agile perspective of things
  • Easy API and a default package-level instance, i.e golog#Fatalf/Errorf/Warnf/Infof/Debugf
  • Fully compatible with the standard library
  • Thanks to the pio library it supports any type of structure, gives you the ability to Hijack and Handle or Intercept the on-going logs too
  • Set or even Add unlimited number of output targets, io.Writer
  • Scan from any io.Reader and log to the defined output target(s)
  • Levels such as fatal,error, warn, info, debug, or disable
  • Beautiful (customizable) colors for leveled logs, automatically omit colors when output does not support colors (i.e files)
  • Incredible high-performant, 3 times faster than your favourite logger
  • Never-Panics

Navigate through _examples and integrations to learn if that fair solution suits your needs.

πŸš€ Installation

The only requirement is the Go Programming Language*.

$ go get github.com/kataras/golog

golog is fairly built on top of the pio library, it has no more external dependencies.

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

πŸ“¦ Projects using golog
Package Author Description
iris Gerasimos Maropoulos The fastest web framework for Go in (THIS) Earth. HTTP/2 Ready-To-GO. Mobile Ready-To-GO.

Do not hesitate to put your package on this list via PR!

Documentation ΒΆ

Overview ΒΆ

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

Installation ΒΆ

The only requirement is the Go Programming Language

$ go get -u github.com/kataras/golog

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
	// that are not support colors,
	// second argument is the full colorful text (yes it can be different if you wish to).
	//
	// If the second argument is empty then golog will update the colorful text to the
	// default color (i.e red on ErrorText) based on the first argument.

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

	// 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",
		RawText: "[SUCC]",
		// ColorfulText (Green Color[SUCC])
		ColorfulText: "\x1b[32m[SUCC]\x1b[0m",
	}

	// 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:
// `golog.Install(logrus.StandardLogger())`
//
// Look `golog#Handle` for more.
Install(logger ExternalLogger)

// InstallStd receives  a standard 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.
//
// Example Code:
//	import "log"
//	myLogger := log.New(os.Stdout, "", 0)
//	InstallStd(myLogger)
//
// Look `golog#Handle` for more.
InstallStd(logger StdLogger)

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.InstallStd(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.0.8"

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

	VerboseText = Levels[VerboseLevel].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 ""
	}
)
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"},
		RawText:          "",
		ColorfulText:     "",
	},
	FatalLevel: {
		Name:    "fatal",
		RawText: "[FTAL]",

		ColorfulText: pio.RedBackground("[FTAL]"),
	},
	ErrorLevel: {
		Name:         "error",
		RawText:      "[ERRO]",
		ColorfulText: pio.Red("[ERRO]"),
	},
	WarnLevel: {
		Name:             "warn",
		AlternativeNames: []string{"warning"},
		RawText:          "[WARN]",
		ColorfulText:     pio.Purple("[WARN]"),
	},
	InfoLevel: {
		Name:         "info",
		RawText:      "[INFO]",
		ColorfulText: pio.LightGreen("[INFO]"),
	},
	DebugLevel: {
		Name:         "debug",
		RawText:      "[DBUG]",
		ColorfulText: pio.Yellow("[DBUG]"),
	},
	VerboseLevel: {
		Name:         "verbose",
		RawText:      "[VBOS]",
		ColorfulText: pio.White("[VBOS]"),
	},
}

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.

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 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 ExternalLogger)

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: `golog.Install(logrus.StandardLogger())`

Look `golog#Handle` for more.

func InstallStd ΒΆ

func InstallStd(logger StdLogger)

InstallStd receives a standard 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.

Example Code:

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

Look `golog#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 SetTimeFormat ΒΆ

func SetTimeFormat(s string)

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

func Verbose ΒΆ

func Verbose(v ...interface{})

Verbose will print when logger's Level is verbose.

func Verbosef ΒΆ

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

Verbosef will print when logger's Level is verbose.

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 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 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
	// VerboseLevel will print on any level, fatals, errors, warnings, infos, debugs and verbose logs.
	VerboseLevel
)

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

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 RawText will be the prefix of the log level
	// when output doesn't supports colors.
	//
	// When RawText is changed its ColorfulText is also changed
	// to a default color, but callers are able to change it too.
	RawText string
	// The ColorfulText will be the prefix of the log level
	// when output supports colors, almost everything except
	// os files and putty-based terminals(?).
	//
	// If ColorfulText is empty then built'n colors
	// are being used to wrap the "RawText".
	ColorfulText string
}

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

func (*LevelMetadata) SetText ΒΆ

func (m *LevelMetadata) SetText(newRawText string, newColorfulText string)

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

If "newRawText" is empty then it will just skip the Text set-ing. If "newColorfulText" is empty then it will update the text color version using the default values by using the new raw text.

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
	// Time is the current time
	Time time.Time
	// Level is the log level.
	Level Level
	// Message is the string reprensetation of the log's main body.
	Message string
	// 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
}

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     []byte
	Level      Level
	TimeFormat string
	// 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
	// contains filtered or unexported fields
}

Logger is our golog.

func Child ΒΆ

func Child(name string) *Logger

Child (creates if not exists and) returns a new child Logger based on the default package-level logger instance.

Can be used to separate logs by category.

func New ΒΆ

func New() *Logger

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

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 (*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(name string) *Logger

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

Can be used to separate logs by category.

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) 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 ExternalLogger)

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

Look `golog#Logger.Handle` for more.

func (*Logger) InstallStd ΒΆ

func (l *Logger) InstallStd(logger StdLogger)

InstallStd receives a standard 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.

Example Code:

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

Look `golog#Logger.Handle` for more.

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) 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) 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) 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 first space-separated word that is being presented to the output. It's written even before the log level text.

Returns itself.

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) Verbose ΒΆ

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

Verbose will print when logger's Level is verbose.

func (*Logger) Verbosef ΒΆ

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

Verbosef will print when logger's Level is verbose.

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.

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.

Jump to

Keyboard shortcuts

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