log

package
v0.0.0-...-0caaa62 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2017 License: GPL-3.0-or-later Imports: 15 Imported by: 3

Documentation

Overview

Package log is a simple colored info and errors logger.

Errors will be displayed only if they are valid, so you can send all your errors without having to bother if they are filled or not. You just have to use it with all errors you want to be displayed and sort the others.

98% code coverage in examples.

Example

Example of a very common case of chained tests in go:

package main

import (
	"errors"

	"github.com/sqp/godock/libs/cdtype"
	"github.com/sqp/godock/libs/log"
)

func NewTestLogger(hist cdtype.LogOut) *log.Log {
	logger := log.NewLog(hist)
	logger.SetName("test")

	logger.SetTimeFormat("")
	logger.SetColorName(nocolor)
	logger.SetColorInfo(nocolor)
	logger.SetColorDebug(nocolor)
	logger.SetColorDEV(nocolor)
	logger.SetColorWarn(nocolor)
	logger.SetColorError(nocolor)
	return logger
}

func nocolor(str string) string { return str }

func main() {
	logger := NewTestLogger(log.Logs) // The logger with its common history.

	testChain := func(isErrGet, isErrParse, isErrUse bool) error {
		data, e := GetSomeData(isErrGet)
		if logger.Err(e, "Get data") { // when we need to keep or forward the error.
			return e
		}

		parsed, e := ParseMyData(data, isErrParse)
		logger.Err(e, "Parse data", "(don't block)") // when we just want to output it.

		result, e := UseData(parsed, isErrParse, isErrUse)
		if logger.Err(e, "Use data") { // used as a simple test.
			return e
		}
		logger.Info("Data used", result)
		return nil
	}

	for _, test := range []struct {
		isErrGet, isErrParse, isErrUse bool
	}{
		{true, false, false},
		{false, true, false},
		{false, false, true},
		{false, false, false},
	} {
		testChain(test.isErrGet, test.isErrParse, test.isErrUse)
	}

}

func GetSomeData(isErrGet bool) (string, error) {
	if isErrGet {
		return "", errors.New("get fail")
	}
	return "get success", nil
}

func ParseMyData(data string, isErrParse bool) (string, error) {
	if isErrParse {
		return "", errors.New("parse fail")
	}
	return "parse success", nil
}

func UseData(parsed string, isErrParse, isErrUse bool) (string, error) {
	if isErrUse {
		return "", errors.New("use fail")
	}
	if isErrParse {
		return "have half data", nil
	}
	return "everything is fine", nil
}
Output:

test [error] Get data : get fail
test [error] Parse data (don't block) : parse fail
test [Data used] have half data
test [error] Use data : use fail
test [Data used] everything is fine

Index

Examples

Constants

This section is empty.

Variables

View Source
var CmdPlaySound = [][]string{
	{"paplay", "--client-name=cairo-dock"},
	{"aplay"},
	{"play"},
}

CmdPlaySound defines simple sound players command and args.

View Source
var Logs = NewHistory()

Logs provides a default history logger.

Functions

This section is empty.

Types

type Fmt

type Fmt struct {
	// contains filtered or unexported fields
}

Fmt formats log messages.

func NewFmt

func NewFmt() *Fmt

NewFmt creates a logging formater.

func (*Fmt) Format

func (f *Fmt) Format(colfunc func(string) string, sender, msg string, more ...interface{}) string

Format returns a formatted message in the given color with endline.

func (*Fmt) FormatErr

func (f *Fmt) FormatErr(e error, level cdtype.LogLevel, sender string, msg ...interface{}) string

FormatErr returns a formatted error message with endline.

func (*Fmt) FormatMsg

func (f *Fmt) FormatMsg(level cdtype.LogLevel, sender string, msg string, more ...interface{}) string

FormatMsg returns a formatted standard message with endline.

func (*Fmt) LevelColor

func (f *Fmt) LevelColor(level cdtype.LogLevel) func(string) string

LevelColor returns the field color formater for the level.

func (*Fmt) SetColorDEV

func (f *Fmt) SetColorDEV(callFormat func(string) string)

SetColorDEV sets the formater used to color the message as third log argument.

func (*Fmt) SetColorDebug

func (f *Fmt) SetColorDebug(callFormat func(string) string)

SetColorDebug sets the formater used to color the message as third log argument.

func (*Fmt) SetColorError

func (f *Fmt) SetColorError(callFormat func(string) string)

SetColorError sets the formater used to color the message as third log argument.

func (*Fmt) SetColorInfo

func (f *Fmt) SetColorInfo(callFormat func(string) string)

SetColorInfo sets the formater used to color the message as third log argument.

func (*Fmt) SetColorName

func (f *Fmt) SetColorName(callFormat func(string) string)

SetColorName sets the formater used to display the sender as second log argument.

func (*Fmt) SetColorWarn

func (f *Fmt) SetColorWarn(callFormat func(string) string)

SetColorWarn sets the formater used to color the message as third log argument.

func (*Fmt) SetTimeFormat

func (f *Fmt) SetTimeFormat(format string)

SetTimeFormat sets the time format displayed as first log argument.

type History

type History struct {
	Fmt // extends the formater
	// contains filtered or unexported fields
}

History provides an history for the Log system.

func NewHistory

func NewHistory(optionalFeeder ...feeder) *History

NewHistory creates a logging history with an optional forwarder.

func (*History) Err

func (hist *History) Err(e error, level cdtype.LogLevel, sender, msg string)

Err logs an error message.

func (*History) List

func (hist *History) List() []cdtype.LogMsg

List returns the log messages saved.

func (*History) Msg

func (hist *History) Msg(level cdtype.LogLevel, sender, msg string, more ...interface{})

Msg logs a standard message.

func (*History) Raw

func (hist *History) Raw(sender, msg string)

Raw logs a raw data message.

func (*History) SetDelay

func (hist *History) SetDelay(d time.Duration)

SetDelay sets how long messages are stored in history.

func (*History) SetTerminal

func (hist *History) SetTerminal(f feeder)

SetTerminal sets the optional terminal forwarder.

func (*History) Write

func (hist *History) Write(p []byte) (n int, err error)

Write saves the log into his history and send it back to the default output. If a terminal is defined, it will have the data forwarded too.

type Log

type Log struct {
	cdtype.LogFmt // extends the formater
	// contains filtered or unexported fields
}

Log is a simple colored info and errors logger.

func NewLog

func NewLog(out cdtype.LogOut) *Log

NewLog creates a logger with the forwarder.

func (*Log) DEV

func (l *Log) DEV(msg string, more ...interface{})

DEV is like Info, but to be used by the dev for his temporary tests.

func (*Log) Debug

func (l *Log) Debug(msg string, more ...interface{})

Debug is to be used every time a useful step is reached in your module activity. It will display the flood to the user only when the debug flag is enabled.

func (*Log) Debugf

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

Debugf log a new debug message with arguments formatting.

func (*Log) Err

func (l *Log) Err(e error, args ...interface{}) (fail bool)

Err test and log the error as Error type. Return true if an error was found.

func (*Log) Errorf

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

Errorf log a new error with arguments formatting.

func (*Log) ExecAsync

func (l *Log) ExecAsync(command string, args ...string) error

ExecAsync run a command with output forwarded to console but don't wait for its completion. Errors will be logged.

func (*Log) ExecCmd

func (l *Log) ExecCmd(command string, args ...string) *exec.Cmd

ExecCmd provides a generic command with output forwarded to console.

func (*Log) ExecShlex

func (l *Log) ExecShlex(command string, args ...string) (*exec.Cmd, error)

ExecShlex parse the command with shlex before returning an ExecCmd.

func (*Log) ExecShow

func (l *Log) ExecShow(command string, args ...string) error

ExecShow run a command with output forwarded to console and wait.

func (*Log) ExecSync

func (l *Log) ExecSync(command string, args ...string) (string, error)

ExecSync run a command with and grab the output to return it when finished.

func (*Log) GetDebug

func (l *Log) GetDebug() bool

GetDebug gets the debug state of the logger.

func (*Log) GoTry

func (l *Log) GoTry(call func())

GoTry launch a secured go routine. Panic will be recovered and logged.

func (*Log) Info

func (l *Log) Info(msg string, more ...interface{})

Info displays normal informations on the standard output, with the first param in green.

func (*Log) Infof

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

Infof log a new info with arguments formatting.

func (*Log) LogOut

func (l *Log) LogOut() cdtype.LogOut

LogOut returns the optional forwarder of the logger.

func (*Log) NewErr

func (l *Log) NewErr(msg string, args ...interface{})

NewErr log a new error.

func (*Log) NewWarn

func (l *Log) NewWarn(msg string, args ...interface{})

NewWarn log a new warning.

func (*Log) PlaySound

func (l *Log) PlaySound(soundFile string) error

PlaySound plays a sound file.

func (*Log) Recover

func (l *Log) Recover()

Recover from crash. Use with defer before a dangerous action.

func (*Log) SetDebug

func (l *Log) SetDebug(debug bool) cdtype.Logger

SetDebug change the debug state of the logger. Only enable or disable messages send with the Debug command.

func (*Log) SetLogOut

func (l *Log) SetLogOut(out cdtype.LogOut) cdtype.Logger

SetLogOut connects the optional forwarder to the logger.

func (*Log) SetName

func (l *Log) SetName(name string) cdtype.Logger

SetName set the displayed and forwarded name for the logger.

func (*Log) Warn

func (l *Log) Warn(e error, args ...interface{}) (fail bool)

Warn test and log the error as warning type. Return true if an error was found.

func (*Log) Warnf

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

Warnf log a new error with arguments formatting.

func (*Log) Write

func (l *Log) Write(p []byte) (n int, err error)

Write forward the stream to the connected logger.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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