golog

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2023 License: BSD-3-Clause Imports: 14 Imported by: 1

README

golog

Build Status GitHub last commit Coverage Status Codacy Badge GoDoc GitHub stars

Versatile Go Logger with a focus on Build Environments to provide performance and information where needed. Also allows setting custom format for messages.

Notice

If you would like to help, please do so. Besides the obvious performance tweaks checkout the issues and do a PR. Please make sure to handle code coverage.

Preview

Example Output (Development) Example Output (Quality Assurance) Example Output (Production) Example Output (JSON)

Install

go get -u github.com/AndrewDonelson/golog

This will either Install or Update the package.

Example

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

package main

import (
   "github.com/AndrewDonelson/golog"
)

func main() {
    // Get the instance for logger class
    // Third option is optional and is instance of type io.Writer, defaults to os.Stderr
    println("\nProduction Output: as Log")
    log, err := golog.NewLogger(&golog.Options{Module: "prod-example"})
    if err != nil {
        panic(err) // Check for error
    }
    log.SetEnvironment(golog.EnvProduction)

    method := "main"
    log.Trace(method, "main.go", 7)
    log.SetFunction(method)

	// Debug
	golog.Log.Debug("This is Debug message!")

	// Show the info
	golog.Log.Info("This is Info message, Fatal & Panic skipped!")

	// Notice
	golog.Log.Notice("This is Notice message!")

	// Show the success
	golog.Log.Success("This is Success message!")

	// Give the Warning
	golog.Log.Warning("This is Warning message!")

	// Show the error
	golog.Log.Error("This is Error message!")

	// RAW log
	golog.Log.Print("This is RAW message!")

	// PrettyPrint log
	golog.Log.Print(golog.PrettyPrint(golog.Log.Options))

	golog.Log.Trace("This is Trace message!", "main.go", 13)
}

Example Usage

You can set a environment variable BUILD_ENV to either [dev, qa or prod] and when a logger is created it will auto-detect and set the proper environment. After creating the logger you may of course manually set the environment by using log.SetEnvironment({EnvDevelopment}). Below are the Options for when creating a Custom Logger:

// Options allow customization of the logger by the end user
type Options struct {
   Module      string      // Name of running module
   Environment Environment // Override default handling
   UseColor    ColorMode   // Enable color (override) default handling
   Out         io.Writer   // Where to write output
   FmtProd     string      // for use with production environment
   FmtDev      string      // for use with development environment
}
Creating New Logger

There is no need to manually create a logger. Simply import golog and start using.

golog.Log.SetModule("myapp")
err := RunSomeFunction()
if err != nil {
   golog.Log.ErrorE(err)
}
Default (minumum)
 // Create a logger with all default options
 log, err := golog.NewLogger(nil)
 if err != nil {
    panic(err) // Check for error
 }
Typical
// create a new golag logger
log, err := golog.NewLogger(&golog.Options{Module: "myapp"})
if err != nil {
   panic(err) // Check for error
}
// You can set the Environment here, or in the above NewLogger() call but suggested way
// is to use an OS Environment variable named "BUILD_ENV" to set either dev or qa. 
// Anything else would be considered production
log.SetEnvironment(golog.EnvProduction)

Custom

 log, err = NewLogger(&Options{Module: "my-service", UseColor: clrDisabled})

This will create a new logger with the module name my-service and color disabled.

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

// Default (minumum)
 log, err := golog.NewLogger(nil)
 if err != nil {
    panic(err) // Check for error
 }
log, _ := logger.New("pkgname", 1)
log.SetFormat(format)

... or for package

golog.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:

Verb Description
%{id} number of current log message
%{module} module name (that you passed to func New())
%{time} current time in format "2006-01-02 15:04:05"
%{time:format} current time in format that you want
%{level} level name (upper case) of log message ("ERROR", "DEBUG", etc)
%{lvl} first 3 letters of level name (upper case) of log message
%{file} name of file in what you wanna write log
%{filename} the same as %{file}
%{line} line number of file in what you wanna write log
%{message} 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 -v .` to run test on logger.
go test -bench .` for benchmarks.

Benchmarks

BenchmarkLoggerNew-12             500000              4557 ns/op
BenchmarkLoggerNewLogger-12       500000              4323 ns/op

Usage

make           # everything
make test      # just run tests
make bencH     # just run benchmarks
make build     # just build examples
make run       # just run examples

Thanks

golog is not a fork, but it was the starting point for the project. I'd like to thank all out there which helped with go-logging.

Following contributors have made major contributions to go-logger:

@qioalice @gjvnq @maezen

License

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

Documentation

Overview

Package golog Simple flexible go logging This file contains all the code for the main logger

Package golog Simple flexible go logging this file contains all the code for Info

Package golog Simple flexible go logging This file contains all un-exported (local) functions

Package golog Simple flexible go logging This file contains logger configuration implementation

Package golog Simple flexible go logging This file contains all code for the worker

Index

Constants

View Source
const (

	// FmtProductionLog is the built-in production log format
	// [000001] [gwfnode] RAW 2023-04-29 07:33:37 golog.go#232 : gwfnode Server [Version 2023.04.28f1.0] (EnvProduction)
	FmtProductionLog = "[%.6[1]d] [%.16[3]s] %.4[7]s %.19[2]s %[5]s#%[6]d : %[8]s"

	// FmtProductionJSON is the built-in production json format
	FmtProductionJSON = "{\"%.16[3]s\",\"%[5]s\",\"%[6]d\",\"%[4]s\",\"%[1]d\",\"%.19[2]s\",\"%[7]s\",\"%[8]s\"}"

	// FmtDevelopmentLog is the built-in development log format
	// [000001] [gwfnode] RAW 2023-04-29 07:33:37 golog.go#232-github.com/NlaakStudiosLLC/io.gwf/sdk/pkgs/util.SetGoLogBuildEnv : gwfnode Server [Version 2023.04.28f1.0] (EnvDevelopment)
	FmtDevelopmentLog = "[%.6[1]d] [%.16[3]s] %.4[7]s %.19[2]s %[5]s#%[6]d-%[4]s : %[8]s"

	// FmtDefault is the default log format
	FmtDefault = FmtProductionLog

	// MaxLogID is the maximum number for log event ids before resetting to 1
	MaxLogID = 999999
)
View Source
const (
	Black = (iota + 30)
	Red
	Green
	Yellow
	Blue
	Magenta
	Cyan
	White
)

Color numbers for stdout

View Source
const (
	RawLevel     = iota + 1 // None
	ErrorLevel              // Red 		31 - Fatal  & Error Levels are same
	TraceLevel              // Magneta	35
	WarningLevel            // Yellow 	33
	SuccessLevel            // Green 	32
	NoticeLevel             // Cyan 	36
	InfoLevel               // White 	37
	DebugLevel              // Blue 	34
)

Log Level. Panic is not included as a level.

Variables

This section is empty.

Functions

func GetCaller added in v1.2.0

func GetCaller(skipLevels int) (function, file string, line int)

GetCaller helper function to get the function name, filename and line number

func GetType added in v1.2.0

func GetType(i interface{}) string

GetType will return the name of the provided interface using reflection

func PrettyPrint added in v1.2.0

func PrettyPrint(v interface{}) string

PrettyPrint is used to display any type nicely in the log output

func Stack

func Stack() string

Stack Returns a string with the execution stack for this goroutine

Types

type ColorMode

type ColorMode int

ColorMode enumeration

const (
	// ClrNotSet - No color mode is set (initial)
	ClrNotSet ColorMode = -1 + iota
	// ClrDisabled - Do not use color. Overrides defaults
	ClrDisabled
	// ClrEnabled - Force use of color. Overrides defaults
	ClrEnabled
	// ClrAuto - Use color based on detected (or set) Environment
	ClrAuto
)

type Environment

type Environment int

Environment enumeration

const (
	// EnvAuto - No Environment set (initial) Will detect by looking for BUILD_ENV os variable
	EnvAuto Environment = 0 + iota

	// EnvDevelopment - All Log levels, color enabled and extra info on errors
	// Log only these levels: All
	EnvDevelopment

	// EnvQuality - No debug level logging, color enabled, no extra info on errors
	// Log only these levels: Info, Notice, Success, Warning, Error and RAW
	EnvQuality

	// EnvProduction - Error level & higher, no color, minimum information
	// Log only these levels: Warning, Error and RAW
	EnvProduction
)

type Info

type Info struct {
	ID         uint64
	Time       string
	Module     string
	Function   string
	Level      LogLevel
	Line       int
	Filename   string
	Message    string
	Duration   time.Duration
	Method     string
	StatusCode int
	Route      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

Output Returns a proper string to be outputted for a particular info

type LogLevel

type LogLevel int

LogLevel type

type Logger

type Logger struct {
	Options Options
	// 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

var (
	// Log is set y the init function to be a default thelogger
	Log *Logger
)

func NewLogger

func NewLogger(opts *Options) *Logger

NewLogger creates and returns new logger for the given model & environment module is the specific module for which we are logging environment overrides detected environment (if -1) color defines whether the output is to be colored or not, out is instance of type io.Writer defaults to os.Stderr

func (*Logger) Debug

func (l *Logger) Debug(a ...interface{})

Debug logs a message at Debug level

func (*Logger) DebugE

func (l *Logger) DebugE(err error)

DebugE logs a error 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) Error

func (l *Logger) Error(a ...interface{})

Error logs a customer message at Error level

func (*Logger) ErrorE

func (l *Logger) ErrorE(err error)

ErrorE logs a error 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) Fatal

func (l *Logger) Fatal(a ...interface{})

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

func (*Logger) FatalE

func (l *Logger) FatalE(err error)

FatalE logs a error at Fatallevel

func (*Logger) Fatalf

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

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

func (*Logger) HandlerLog

func (l *Logger) HandlerLog(w http.ResponseWriter, r *http.Request)

HandlerLog Traces & logs a message at Debug level for a REST handler

func (*Logger) HandlerLogf

func (l *Logger) HandlerLogf(w http.ResponseWriter, r *http.Request, format string, a ...interface{})

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

func (*Logger) Info

func (l *Logger) Info(a ...interface{})

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

func (l *Logger) Log(lvl LogLevel, a ...interface{})

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

func (*Logger) Notice

func (l *Logger) Notice(a ...interface{})

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

func (l *Logger) Panic(a ...interface{})

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

func (*Logger) PanicE

func (l *Logger) PanicE(err error)

PanicE logs a error at Fatallevel

func (*Logger) Panicf

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

Panicf is just like func l.FatalF except that it is followed by a call to panic

func (*Logger) Print

func (l *Logger) Print(a ...interface{})

Print logs a message at directly with no level (RAW)

func (*Logger) Printf

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

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

func (*Logger) SetColor added in v1.1.0

func (l *Logger) SetColor(c ColorMode)

SetColor is used to manually set the color mode

func (*Logger) SetEnvironment

func (l *Logger) SetEnvironment(env Environment)

SetEnvironment is used to manually set the log environment to either development, testing or production

func (*Logger) SetEnvironmentFromString added in v1.1.0

func (l *Logger) SetEnvironmentFromString(env string)

SetEnvironmentFromString is used to manually set the log environment to either development, testing or production

func (*Logger) SetFormat

func (l *Logger) SetFormat(format string)

SetFormat ...

func (*Logger) SetFunction

func (l *Logger) SetFunction(name string)

SetFunction sets the function name of the logger

func (*Logger) SetLogLevel

func (l *Logger) SetLogLevel(level LogLevel)

SetLogLevel ...

func (*Logger) SetModuleName

func (l *Logger) SetModuleName(name string)

SetModuleName sets the name of the module being logged

func (*Logger) SetOutput

func (l *Logger) SetOutput(out io.Writer)

SetOutput is used to manually set the output to send log data

func (*Logger) StackAsError

func (l *Logger) StackAsError(message string)

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

func (*Logger) StackAsFatal added in v1.1.0

func (l *Logger) StackAsFatal(message string)

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

func (*Logger) Success

func (l *Logger) Success(a ...interface{})

Success logs a message at Success level

func (*Logger) Successf

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

Successf logs a message at Success level using the same syntax and options as fmt.Printf

func (*Logger) Trace

func (l *Logger) Trace(name, file string, line int)

Trace is a basic timing function that will log InfoLevel duration of name

func (*Logger) UseJSONForProduction

func (l *Logger) UseJSONForProduction()

UseJSONForProduction forces using JSON instead of log for production

func (*Logger) Warning

func (l *Logger) Warning(a ...interface{})

Warning logs a message at Warning level

func (*Logger) WarningE

func (l *Logger) WarningE(err error)

WarningE logs a error 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

type Options

type Options struct {
	Module      string      // Name of running module
	Environment Environment // Override default handling
	UseColor    ColorMode   // Enable color (override) default handling
	SmartError  bool        // Extended error that adapts by environment
	Out         io.Writer   // Where to write output
	FmtProd     string      // for use with production environment
	FmtDev      string      // for use with development environment
	Testing     bool        // This is set to true if go testing is detected
}

Options allow customization of the logger by the end user

func NewCustomOptions

func NewCustomOptions(module string, env Environment, clr ColorMode, SmartError bool, out io.Writer, fmtProd, fmtDev string) *Options

NewCustomOptions returns a new Options object with all user options

func NewDefaultOptions

func NewDefaultOptions() *Options

NewDefaultOptions returns a new Options object with all defaults

func (*Options) EnvAsString

func (o *Options) EnvAsString() string

EnvAsString returns the current envirnment for options as a string

type Worker

type Worker struct {
	Minion *log.Logger
	// 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 ColorMode, out io.Writer) *Worker

NewWorker 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) GetEnvironment

func (w *Worker) GetEnvironment() Environment

GetEnvironment returns the currently set environment for the worker

func (*Worker) Log

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

Log Function of Worker class to log a string based on level

func (*Worker) SetEnvironment

func (w *Worker) SetEnvironment(env Environment)

SetEnvironment is used to manually set the log environment to either development, testing or production

func (*Worker) SetFormat

func (w *Worker) SetFormat(format string)

SetFormat ...

func (*Worker) SetFunction

func (w *Worker) SetFunction(name string)

SetFunction sets the function name ofr the worker

func (*Worker) SetLogLevel

func (w *Worker) SetLogLevel(level LogLevel)

SetLogLevel ...

func (*Worker) SetOutput

func (w *Worker) SetOutput(out io.Writer)

SetOutput is used to manually set the output to send log data

func (*Worker) UseJSONForProduction

func (w *Worker) UseJSONForProduction()

UseJSONForProduction forces using JSON instead of log for production

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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