log

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

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

Go to latest
Published: Feb 10, 2021 License: MIT Imports: 6 Imported by: 22

README

Basic logging with batteries

Build Status Coverage Status GoDoc GitPitch

  • APIs to prefix log-level in log messages.
  • Global option to redirect logs to a file.
  • Include/Exclude/Format log time.
  • Colorize log messages for different levels.
  • Console logging.
  • Stable APIs, existing APIs are not going to change.

How to use golog

Packages can import golog and use its methods

import github.com/bnclabs/golog
func myfunc() {
    ..
    log.Fatalf(...)
    ..
    log.Warnf(...)
    ..
    log.Debugf(...)
}

Note here that log is not an object name, importing golog resolves to log package that has exported methods Fatalf() Warnf() etc ... For more information please read the go-documentation for log package.

By default, importing the package will initialize the logger to default-logger that shall log to standard output. To use custom logger use the following initializer function in your package or application:

import github.com/bnclabs/golog

var mylogger = newmylogger()
func init() {
    setts := map[string]interface{}{
        "log.level": "info",
        "log.file":  "",
    }
    SetLogger(mylogger, setts)
}

mylogger should implement the log.Logger interface{}.

Order of log levels

const (
	logLevelIgnore LogLevel = iota + 1
	logLevelFatal
	logLevelError
	logLevelWarn
	logLevelInfo
	logLevelVerbose
	logLevelDebug
	logLevelTrace
)

Console Logging

By default log APIs will worry about log-level, prefix format, time-format sometimes it become too much of clutter on the screen to communicate simple messages with user via console. In such cases use the Consolef API.

    log.Consolef("goledger version - goledger%v\n", api.LedgerVersion)

Consolef does not print the log time, log level and always outputs to stdout.

Settings

  • log.level, filter all messages logged at level greater than the configured value. Can be one of the following names - ignore, fatal, error, warn, info, verbose, debug, trace
  • log.flag, comma separated value of log.Flags, eg: Ldate,Ltime,Llongfile, described further down.
  • log.file, if not empty string, all log messages are appended to configured file.
  • log.timeformat, format of time string prefixed to log message, should confirm to time.Now().Format().
  • log.prefix, fmt.Sprintf format string for log level, by default [<leve>] format is used.
  • log.colorfatal, comma separated value of attribute names - bold, underline, blinkslow, blinkrapid, crossedout, red, green, yellow, blue, magenta, cyan, white, hired, higreen, hiyellow, hiblue, himagenta, hicyan, hiwhite. Attribute-settings available for all log levels.

Ignore ignore level can be used to ignore all log messages. Note that only log-level can be specified as ignore, no corresponding API is supported.

log.flags

const (
    // Bits or'ed together to control what's printed.
    // There is no control over the order they appear (the order listed
    // here) or the format they present (as described in the comments).
    // The prefix is followed by a colon only when Llongfile or Lshortfile
    // is specified.
    // For example, flags Ldate | Ltime (or LstdFlags) produce,
    //  2009/01/23 01:23:23 message
    // while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
    //  2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
    Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
    Ltime                         // the time in the local time zone: 01:23:23
    Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
    Llongfile                     // full file name and line number: /a/b/c/d.go:23
    Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
    LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
    LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

Default log.level is Info.

Panic and recovery

  • API SetLogger()
    • If log.file is not string.
    • If creating or opening log.file fails.
    • If log.level is not an allowed log string.
    • If log.prefix is neither string, nor bool.
  • API SetLogLevel()
    • If log.level is not an allowed log string.
  • API SetLogprefix()
    • If log.prefix is neither string, nor bool.

Typically all the above panic cases needs to be fixed during development, and should never occur during production. If panics become unavoidable please use panic/recover.

How to contribute

  • Pick an issue, or create an new issue. Provide adequate documentation for the issue.
  • Assign the issue or get it assigned.
  • Work on the code, once finished, raise a pull request.
  • Golog is written in golang, hence expected to follow the global guidelines for writing go programs.
  • As of now, branch master is the development branch.

Documentation

Overview

Package golog provides a simple alternative to standard log that defines a Logger interface allowing custom logger to be used across the application and its libraries.

To begin with, import the golog package and start using its exported functions like:

import "github.com/bnclabs/golog"
...
log.Printf()
log.Fatalf()

Default logger will be used in the above case. To configure default logger:

setts := map[string]interface{}{
	"log.level":        "info",
	"log.flags":        "",
	"log.file":         "",
	"log.timeformat":   timeformat,
	"log.prefix":       prefix,
	"log.colorignore":  "",
	"log.colorfatal":   "red",
	"log.colorerror":   "hired",
	"log.colorwarn":    "yellow",
	"log.colorinfo":    "",
	"log.colorverbose": "",
	"log.colordebug":   "",
	"log.colortrace":   "",
}
log.SetLogger(nil, setts)

Default logger will be configured to "info" level. Refer Defaultsettings() for description on each settings parameter.

To configure a custom logger:

log.Setlogger(customlogger, nil)

Note that `customlogger` should implement the Logger interface.

Index

Constants

This section is empty.

Variables

View Source
var DefaultLogLevel = "info"

DefaultLogLevel to use if log.level option is missing.

Functions

func Consolef

func Consolef(format string, v ...interface{})

Consolef similar to Printf, will log to os.Stdout.

func Debugf

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

Debugf similar to Printf, will be logged only when log level is set as "debug" or above.

func Defaultsettings

func Defaultsettings() map[string]interface{}

Defaultsettings used on default logger.

log.level: (default "info")

Level can be one of the following string,
"ignore", "fatal", "error", "warn", "info", "verbose",
"debug", "trace".

log.flags: (default "")

Flags can be comma seperated string values. These flags as exactly
same as the golang's standard logger.
"ldate" the date in the local time zone: 2009/01/23
"ltime" the time in the local time zone: 01:23:23
"lmicroseconds" microsecond resolution: 01:23:23.123123.
"llongfile" full file name and line number: /a/b/c/d.go:23
"lshortfile" final file name element and line number: d.go:23.
"lutc" if Ldate or Ltime is set, use UTC rather than the local time zone
"lstdflags" initial values for the standard logger ldate,ltime

log.file: (default os.Stdout)

Optional log file name to log o/p. Except Consolef all functions
will o/p to this file if supplied, else to standard output.

log.timeformat: "2006-01-02T15:04:05.999Z-07:00"

Log line timeformat.

log.prefix: [%v]

Prefix format for log-level.

log.colorfatal: "red"

Output color for fatal level.

log.colorerror: "hired"

Output color for error level.

log.colorwarn: "yellow"

Output color for warn level.

log.colorinfo: ""

Output color for info level.

log.colorverbose: "",

Output color for verbose level.

log.colordebug: "",

Output color for debug level.

log.colortrace: "",

Output color for trace level.

func Errorf

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

Errorf similar to Printf, will be logged only when log level is set as "error" or above.

func Fatalf

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

Fatalf similar to Printf, will be logged only when log level is set as "fatal" or above.

func Infof

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

Infof similar to Printf, will be logged only when log level is set as "info" or above.

func Tracef

func Tracef(format string, v ...interface{})

Tracef similar to Printf, will be logged only when log level is set as "trace" or above.

func Verbosef

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

Verbosef similar to Printf, will be logged only when log level is set as "verbose" or above.

func Warnf

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

Warnf similar to Printf, will be logged only when log level is set as "warn" or above.

Types

type LogLevel

type LogLevel int

LogLevel defines application log level.

func (LogLevel) String

func (l LogLevel) String() string

type Logger

type Logger interface {
	// SetLogLevel application's global log level, can be one of the
	// following: "ignore", "fatal", "error", "warn", "info", "verbose",
	// "debug", "trace"
	SetLogLevel(string)

	// SetLogFlags format of log prefix, following golang's log:Flag()
	// specification
	SetLogFlags(flags int)

	// SetTimeFormat to use as prefix for all log messages.
	SetTimeFormat(string)

	// SetLogprefix including the log level.
	SetLogprefix(interface{})

	// SetLogcolor sets coloring attributes for specified log level, can be
	// a list of following attributes: "bold", "underline", "blinkslow",
	// "blinkrapid", "crossedout",
	// "red", "green", "yellow", "blue", "magenta", "cyan", "white"
	// "hired", "higreen", "hiyellow", "hiblue", "himagenta", "hicyan",
	// "hiwhite"
	SetLogcolor(level string, attrs []string)

	// Fatalf similar to Printf, will be logged only when log level is set as
	// "fatal" or above.
	Fatalf(format string, v ...interface{})

	// Errorf similar to Printf, will be logged only when log level is set as
	// "error" or above.
	Errorf(format string, v ...interface{})

	// Warnf similar to Printf, will be logged only when log level is set as
	// "warn" or above.
	Warnf(format string, v ...interface{})

	// Infof similar to Printf, will be logged only when log level is set as
	// "info" or above.
	Infof(format string, v ...interface{})

	// Verbosef similar to Printf, will be logged only when log level is set as
	// "verbose" or above.
	Verbosef(format string, v ...interface{})

	// Debugf similar to Printf, will be logged only when log level is set as
	// "debug" or above.
	Debugf(format string, v ...interface{})

	// Tracef similar to Printf, will be logged only when log level is set as
	// "trace" or above.
	Tracef(format string, v ...interface{})

	// Printlf reserved for future extension.
	Printlf(loglevel LogLevel, format string, v ...interface{})
}

Logger interface for application logging, applications can supply a logger object implementing this interface, otherwise, defaultLogger{} will be used.

func SetLogger

func SetLogger(logger Logger, setts map[string]interface{}) Logger

SetLogger to integrate storage logging with application logging. importing this package will initialize the logger with info level logging to console.

Directories

Path Synopsis
template

Jump to

Keyboard shortcuts

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