slogan

package module
v0.0.0-...-eb3a144 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2023 License: MIT Imports: 11 Imported by: 0

README

slogan

slogan is a logger library for Golang.

Features :

  • 10 Levels from "silent" to "trace", including POSIX levels
  • Configurable format
  • Configurable colors on individual items
  • Easy elapsed time

Howto

Declare use
import (
	"github.com/crownedgrouse/slogan"
)

An alias (here 'log') can be used by setting it before import :

import (
	log  "github.com/crownedgrouse/slogan"
)
Init
package main

import (
	log  	"github.com/crownedgrouse/slogan"
)

func main() {	
	
	log.SetExitOnError(true) 

	// Set verbosity
	log.SetVerbosity(log.Ltrace)
	//
	log.Runtime()
	log.Trace(map[string]string{"this is a": "map"})
	log.Debug("A debug message")
	log.Info("An informative message")
	log.Notice("A notification")
	log.Warning("A warning")
	log.Error("An Error")
	log.Critical("A critical message")
	log.Alert("An alert")
	log.Emergency("An Emergency")
}

Will produce (color not visible in this example):

$ go build
$ ./main
   debug     OS:linux ARCH:386 CPU:4 COMPILER:gc ROOT:/home/eric/git/goroot
   trace     map[string]string
 %v: map[this is a:map]

%v+: map[this is a:map]

%#v: map[string]string{"this is a":"map"}
   debug     A debug message
   info      An informative message
   notice    A notification
   warning   A warning
   error     An Error
   debug     Immediate exit with code 4
$ echo $?
4

Utilities

Show Runtime infos

Runtime informations can be easily shown as a debug level with a uniq call.

slogan.Runtime()
   debug     OS:linux ARCH:386 CPU:4 COMPILER:gc ROOT:/home/eric/git/goroot
Trace Go values

Call to Trace/1 will produce a trace log made of several lines. First line with 'trace' level and type of the value given. Below is written three usual ways to display Go values (%v, %v+ and %#v) separated with an empty line. This format can be overrriden by your own preference (See 'Configuring/Formats' below).

	slogan.Trace(Something)
Time elapsed

Display how many time elapsed since program start or since last call to ElapsedTime() .

    // Show time elapsed since last call to ElapsedTime() or since beginning at first call
    slogan.ElapsedTime()
    // Show time elapsed since beginning. This will reset start time reference
    slogan.AllDone()

Output will be a notice :

  notice    All done in : 296.538µs

Configuring

slogan can be configured at beginning of your program (and also at any time inside your program).

Tags

Tags can be changed by overwritting tags map, with GetTags/0 and SetTags/1.

var tags = [10]string{
		"",          // Prefix
		"emergency", // 1
		"alert    ", // 2
		"critical ", // 3
		"error    ", // 4
		"warning  ", // 5
		"notice   ", // 6
		"info     ", // 7
		"debug    ", // 8
		"trace    ", // 9
}

Output

Default output is on STDERR. Output can be set in a file by passing File Descriptor to "slogan".

	f, err := os.OpenFile("/var/log/myown.log", os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		log.Critical("Cannot open file")
	}
	log.SetOutput(f)

Color will be disabled if output is not a Terminal unless forcing it.

    log.SetForceColor(true)

slogan is using legacy "log" package underneath. SetFlags can be used to change "log" parameters.

For instance to show caller and line number in code :

	slogan.SetFlags(slogan.Lshortfile)  // No need to import "log". Same constants used in "slogan".

Will produce something like below :

   debug     main.go:17     A debug message
   info      main.go:18     An informative message
   notice    main.go:20     A warning
   error     main.go:21     An Error

as well date/time information can be set this way.

Set a prefix to any log :

	log.SetPrefix("===> ")
Behaviour

Considering Warning as Error (and potentialy exit) :

	log.SetWarningAsError(true)

Set or change verbosity from 0 (silent) to 9 (debug) :

slogan.SetVerbosity(0)              // Silent totally logs
slogan.SetVerbosity(slogan.Lsilent) // Same but using "slogan" Levels constant

By setting verbosity, all logs with level lower or equal will be generated (if no immediate exit on error was set and no error occured) :

log.SetExitOnError(true) // Exit if log level reach Error or worst.

If the case, the error message is generated and a debug level may appear, depending current verbosity, indicating that an immediate exit occured, and telling what is the program exit code. The exit code is equal to the level reached by the last fatal error, i.e 1 (emergency) to 4 (error) , or even 5 if warning considered error.

Set option to silent empty log messages :

slogan.SetNoEmpty(true) // Silent empty messages

Note: Exit on error is done even if message is empty and option set.

Formats

Formats can be configured by settings new "Sprintf" values to the three arguments passed to slogan functions :

  • tag %[1]s
  • log %[2]s
  • caller (path:line) %[3]s (only if caller is required in "log" parameters)
// Get current map
formats := slogan.GetFormats()
// Override format for caller : set caller in first
formats["caller"]= "%-25[3]s %[1]s %[2]s "
slogan.SetFormats(formats)
slogan.SetFlags(log.Lshortfile) // caller is required to be shown

Default formats are :

var formats = map[string]string{
	"fatal"   : "Immediate exit with code %d",                        // immediate exit on error format
	"trace"   : "%[1]T\n %%v: %[1]v\n\n%%v+: %+[1]v\n\n%%#v: %#[1]v", // multiline trace format
	"empty"   : "%#v",                                                // trace format for empty variable (avoid unuseful multiline)
	"runtime" : "OS:%s ARCH:%s CPU:%d COMPILER:%s ROOT:%s",           // runtime infos format
	"default" : "   %[1]s %[2]s",                                     // default log format
	"caller"  : "   %[1]s %[3]s\t %[2]s",                             // default log format with caller (where)
	"where"   : "%s:%d",                                              // format for caller location path:linenumber
	"alldone" : "All done in : %s",                                   // all done time format
	"elapsed" : "Elapsed time : %s",                                  // elapsed time format
}
Colors

Color will be disabled if output is not a terminal. This can be avoid however by calling SetForceColor/1 .

Colors can be changed by overwritting colors map, with GetColors/0 and SetColors/1.

See here for possible colors and other output (reverse, underlining, etc.)

var colors = map[int]string{
	10: "Underline",    // Caller
	9:  "DarkGray",     // trace
	8:  "DarkGray",     // debug
	7:  "Purple",       // info
	6:  "Green",        // notice
	5:  "Yellow",       // warning
	4:  "LightRed",     // error
	3:  "Red",          // critical
	2:  "BLightRed",    // alert
	1:  "BRed",         // emergency
	0:  "",             // Prefix
}

As well colorization of elements (called 'parts') in log line can be tuned by changing parts map, with GetParts/0 and SetParts/1

var parts = map[string]bool{
	"caller": true,            // colorize caller (event if it is underlining)
	"tag":    true,            // colorize tag
	"log":    false,           // do not colorize log entry
	"prefix": false,           // do not colorize prefix
}

Documentation

Overview

slogan is a logger library for Golang.

Index

Constants

View Source
const (
	Lsilent    = 0
	Lemergency = 1
	Lalert     = 2
	Lcritical  = 3
	Lerror     = 4
	Lwarning   = 5
	Lnotice    = 6
	Linfo      = 7
	Ldebug     = 8
	Ltrace     = 9
)

Contants for log levels

View Source
const (
	Ldate         = log.Ldate
	Ltime         = log.Ltime
	Lmicroseconds = log.Lmicroseconds
	Llongfile     = log.Llongfile
	Lshortfile    = log.Lshortfile
	LUTC          = log.LUTC
	LstdFlags     = log.Ldate | log.Ltime
)

Contants for legacy log package

Variables

View Source
var CallerBase bool = true

should show only basename of caller

View Source
var Colorize bool = true

should colorize ?

View Source
var ExitOnError bool = false

should exit on error ?

View Source
var ForceColorize bool = false

should colorize even if output is not a terminal ?

View Source
var NoEmpty bool = false

should empty log string logged ?

View Source
var TraceCaller bool = false

should trace caller ?

View Source
var Verbosity int = Lwarning

verbosity

View Source
var WarningAsError bool = false

should warning be error ?

Functions

func Alert

func Alert(log string)

Alert log

func AllDone

func AllDone()

Notice Time elapsed since start and reset start time reference

func Critical

func Critical(log string)

Critical log

func Debug

func Debug(log string)

Debug log

func ElapsedTime

func ElapsedTime()

Notice Time elapsed since last call to this function or since start otherwise and reset time reference

func Emergency

func Emergency(log string)

Emegency log

func Error

func Error(log string)

Error log

func GetColors

func GetColors() map[int]string

Get color map

func GetFormats

func GetFormats() map[string]string

Get format map

func GetParts

func GetParts() map[string]bool

Get parts map

func GetTags

func GetTags() [10]string

Get tag map

func Info

func Info(log string)

Info log

func IsTerminal

func IsTerminal() bool

Get status of output, whether it is a terminal or not

func Log

func Log(level int, log string)

Main log function. 1st argument is level integer, 2nd argument log string

func Notice

func Notice(log string)

Notice log

func Runtime

func Runtime()

Log runtime infos as debug

func SetColor

func SetColor(mode bool)

Colorize or not

func SetColors

func SetColors(n map[int]string) map[int]string

Set new color map and return former map

func SetExitOnError

func SetExitOnError(mode bool)

Set exit on level error or higher

func SetFlags

func SetFlags(flag int)

API for logger override

func SetForceColor

func SetForceColor(mode bool)

Force colorization even if not a terminal

func SetFormats

func SetFormats(n map[string]string) map[string]string

Set a new format map and return former map

func SetNoEmpty

func SetNoEmpty(mode bool)

func SetOutput

func SetOutput(w io.Writer)

Set an io.Writer to log output

func SetParts

func SetParts(n map[string]bool) map[string]bool

Set new parts map and return former map

func SetPrefix

func SetPrefix(prefix string) string

Set a prefix to log entries and return former prefix

func SetTags

func SetTags(n [10]string) [10]string

Set a new tag map and return former map

func SetTraceCaller

func SetTraceCaller(mode bool)

Set caller information in Trace

func SetVerbosity

func SetVerbosity(level int)

Set global verbosity

func SetWarningAsError

func SetWarningAsError(mode bool)

Set warning as error

func ShowColors

func ShowColors()

Display color map

func ShowFormats

func ShowFormats()

Display format map

func ShowParts

func ShowParts()

Display parts map

func ShowTags

func ShowTags()

Display tag map

func Silent

func Silent(log string)

Silent a log while keeping it

func Trace

func Trace(trace interface{})

Trace log Use 'empty' format for empty thing to be trace

func TraceCall

func TraceCall(trace interface{})

Trace log with caller punctually

func TraceCall_

func TraceCall_(trace interface{})

Silent trace and avoid 'declared and not used' build errors

func Trace_

func Trace_(trace interface{})

Silent trace and avoid 'declared and not used' build errors

func Warning

func Warning(log string)

Warning log

Types

This section is empty.

Jump to

Keyboard shortcuts

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