logger

package module
Version: v0.0.0-...-b0d6ccf Latest Latest
Warning

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

Go to latest
Published: May 15, 2019 License: BSD-3-Clause Imports: 10 Imported by: 29

README

go-logger

Build Status GoDoc

A simple go logger for easy logging in your programs. Allows setting custom format for messages.

Preview

Example Output

Install

go get github.com/apsdehal/go-logger

Use go get -u to update the package.

Example

Example program demonstrates how to use the logger. See below for formatting instructions.

package main

import (
	"github.com/apsdehal/go-logger"
	"os"
)

func main () {
	// Get the instance for logger class, "test" is the module name, 1 is used to
	// state if we want coloring
	// Third option is optional and is instance of type io.Writer, defaults to os.Stderr
	log, err := logger.New("test", 1, os.Stdout)
	if err != nil {
		panic(err) // Check for error
	}

	// Critically log critical
	log.Critical("This is Critical!")
	log.CriticalF("%+v", err)
	// You can also use fmt compliant naming scheme such as log.Criticalf, log.Panicf etc
	// with small 'f'
	
	// Debug
	// Since default logging level is Info this won't print anything
	log.Debug("This is Debug!")
	log.DebugF("Here are some numbers: %d %d %f", 10, -3, 3.14)
	// Give the Warning
	log.Warning("This is Warning!")
	log.WarningF("This is Warning!")
	// Show the error
	log.Error("This is Error!")
	log.ErrorF("This is Error!")
	// Notice
	log.Notice("This is Notice!")
	log.NoticeF("%s %s", "This", "is Notice!")
	// Show the info
	log.Info("This is Info!")
	log.InfoF("This is %s!", "Info")

	log.StackAsError("Message before printing stack");

	// Show warning with format
	log.SetFormat("[%{module}] [%{level}] %{message}")
	log.Warning("This is Warning!") // output: "[test] [WARNING] This is Warning!"
	// Also you can set your format as default format for all new loggers
	logger.SetDefaultFormat("%{message}")
	log2, _ := logger.New("pkg", 1, os.Stdout)
	log2.Error("This is Error!") // output: "This is Error!"

	// Use log levels to set your log priority
	log2.SetLogLevel(DebugLevel)
	// This will be printed
	log2.Debug("This is debug!")
	log2.SetLogLevel(WarningLevel)
	// This won't be printed
	log2.Info("This is an error!")
}

Formatting

By default all log messages have format that you can see above (on pic). But you can override the default format and set format that you want.

You can do it for Logger instance (after creating logger) ...

log, _ := logger.New("pkgname", 1)
log.SetFormat(format)

... or for package

logger.SetDefaultFormat(format)

If you do it for package, all existing loggers will print log messages with format that these used already. But all newest loggers (which will be created after changing format for package) will use your specified format.

But anyway after this, you can still set format of message for specific Logger instance.

Format of log message must contains verbs that represent some info about current log entry. Ofc, format can contain not only verbs but also something else (for example text, digits, symbols, etc)

Format verbs:

You can use the following verbs:

%{id}           - means number of current log message
%{module}       - means module name (that you passed to func New())
%{time}			- means current time in format "2006-01-02 15:04:05"
%{time:format}	- means current time in format that you want
					(supports all formats supported by go package "time")
%{level}		- means level name (upper case) of log message ("ERROR", "DEBUG", etc)
%{lvl}			- means first 3 letters of level name (upper case) of log message ("ERR", "DEB", etc)
%{file} 		- means name of file in what you wanna write log
%{filename}		- means the same as %{file}
%{line}			- means line number of file in what you wanna write log
%{message}		- means your log message

Non-existent verbs (like %{nonex-verb} or %{}) will be replaced by an empty string. Invalid verbs (like %{inv-verb) will be treated as plain text.

Tests

Run:

  • go test logger to run test on logger.
  • go test -bench=. for benchmarks.

Thanks

Thanks goes to all go-loggers out there which I used as reference.

Contributors

Following contributors have made major contributions to go-logger:

License

The BSD 3-Clause license, the same as the Go language.

Documentation

Overview

Package name declaration

Index

Constants

View Source
const (
	Black = (iota + 30)
	Red
	Green
	Yellow
	Blue
	Magenta
	Cyan
	White
)

Color numbers for stdout

Variables

This section is empty.

Functions

func SetDefaultFormat

func SetDefaultFormat(format string)

func Stack

func Stack() string

Returns a string with the execution stack for this goroutine

Types

type Info

type Info struct {
	Id       uint64
	Time     string
	Module   string
	Level    LogLevel
	Line     int
	Filename string
	Message  string
}

Info class, Contains all the info on what has to logged, time is the current time, Module is the specific module For which we are logging, level is the state, importance and type of message logged, Message contains the string to be logged, format is the format of string to be passed to sprintf

func (*Info) Output

func (r *Info) Output(format string) string

Returns a proper string to be outputted for a particular info

type LogLevel

type LogLevel int

LogLevel type

const (
	CriticalLevel LogLevel = iota + 1
	ErrorLevel
	WarningLevel
	NoticeLevel
	InfoLevel
	DebugLevel
)

Log Level

type Logger

type Logger struct {
	Module string
	// contains filtered or unexported fields
}

Logger class that is an interface to user to log messages, Module is the module for which we are testing worker is variable of Worker class that is used in bottom layers to log the message

func New

func New(args ...interface{}) (*Logger, error)

Returns a new instance of logger class, module is the specific module for which we are logging , color defines whether the output is to be colored or not, out is instance of type io.Writer defaults to os.Stderr

func (*Logger) Critical

func (l *Logger) Critical(message string)

Critical logs a message at a Critical Level

func (*Logger) CriticalF

func (l *Logger) CriticalF(format string, a ...interface{})

CriticalF logs a message at Critical level using the same syntax and options as fmt.Printf

func (*Logger) Criticalf

func (l *Logger) Criticalf(format string, a ...interface{})

CriticalF logs a message at Critical level using the same syntax and options as fmt.Printf

func (*Logger) Debug

func (l *Logger) Debug(message string)

Debug logs a message at Debug level

func (*Logger) DebugF

func (l *Logger) DebugF(format string, a ...interface{})

DebugF logs a message at Debug level using the same syntax and options as fmt.Printf

func (*Logger) Debugf

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

DebugF logs a message at Debug level using the same syntax and options as fmt.Printf

func (*Logger) Error

func (l *Logger) Error(message string)

Error logs a message at Error level

func (*Logger) ErrorF

func (l *Logger) ErrorF(format string, a ...interface{})

ErrorF logs a message at Error level using the same syntax and options as fmt.Printf

func (*Logger) Errorf

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

ErrorF logs a message at Error level using the same syntax and options as fmt.Printf

func (*Logger) Fatal

func (l *Logger) Fatal(message string)

Fatal is just like func l.Critical logger except that it is followed by exit to program

func (*Logger) FatalF

func (l *Logger) FatalF(format string, a ...interface{})

FatalF is just like func l.CriticalF logger except that it is followed by exit to program

func (*Logger) Fatalf

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

FatalF is just like func l.CriticalF logger except that it is followed by exit to program

func (*Logger) Info

func (l *Logger) Info(message string)

Info logs a message at Info level

func (*Logger) InfoF

func (l *Logger) InfoF(format string, a ...interface{})

InfoF logs a message at Info level using the same syntax and options as fmt.Printf

func (*Logger) Infof

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

InfoF logs a message at Info level using the same syntax and options as fmt.Printf

func (*Logger) Log

func (l *Logger) Log(lvl LogLevel, message string)

The log commnand is the function available to user to log message, lvl specifies the degree of the messagethe user wants to log, message is the info user wants to log

func (*Logger) Notice

func (l *Logger) Notice(message string)

Notice logs a message at Notice level

func (*Logger) NoticeF

func (l *Logger) NoticeF(format string, a ...interface{})

NoticeF logs a message at Notice level using the same syntax and options as fmt.Printf

func (*Logger) Noticef

func (l *Logger) Noticef(format string, a ...interface{})

NoticeF logs a message at Notice level using the same syntax and options as fmt.Printf

func (*Logger) Panic

func (l *Logger) Panic(message string)

Panic is just like func l.Critical except that it is followed by a call to panic

func (*Logger) PanicF

func (l *Logger) PanicF(format string, a ...interface{})

PanicF is just like func l.CriticalF except that it is followed by a call to panic

func (*Logger) Panicf

func (l *Logger) Panicf(format string, a ...interface{})

PanicF is just like func l.CriticalF except that it is followed by a call to panic

func (*Logger) SetFormat

func (l *Logger) SetFormat(format string)

func (*Logger) SetLogLevel

func (l *Logger) SetLogLevel(level LogLevel)

func (*Logger) StackAsCritical

func (l *Logger) StackAsCritical(message string)

Prints this goroutine's execution stack as critical with an optional message at the begining

func (*Logger) StackAsError

func (l *Logger) StackAsError(message string)

Prints this goroutine's execution stack as an error with an optional message at the begining

func (*Logger) Warning

func (l *Logger) Warning(message string)

Warning logs a message at Warning level

func (*Logger) WarningF

func (l *Logger) WarningF(format string, a ...interface{})

WarningF logs a message at Warning level using the same syntax and options as fmt.Printf

func (*Logger) Warningf

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

WarningF logs a message at Warning level using the same syntax and options as fmt.Printf

type Worker

type Worker struct {
	Minion *log.Logger
	Color  int
	// contains filtered or unexported fields
}

Worker class, Worker is a log object used to log messages and Color specifies if colored output is to be produced

func NewWorker

func NewWorker(prefix string, flag int, color int, out io.Writer) *Worker

Returns an instance of worker class, prefix is the string attached to every log, flag determine the log params, color parameters verifies whether we need colored outputs or not

func (*Worker) Log

func (w *Worker) Log(level LogLevel, calldepth int, info *Info) error

Function of Worker class to log a string based on level

func (*Worker) SetFormat

func (w *Worker) SetFormat(format string)

func (*Worker) SetLogLevel

func (w *Worker) SetLogLevel(level LogLevel)

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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