README
¶
golog
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
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:
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
- func GetCaller(skipLevels int) (function, file string, line int)
- func GetType(i interface{}) string
- func PrettyPrint(v interface{}) string
- func Stack() string
- type ColorMode
- type Environment
- type Info
- type LogLevel
- type Logger
- func (l *Logger) Debug(a ...interface{})
- func (l *Logger) DebugE(err error)
- func (l *Logger) Debugf(format string, a ...interface{})
- func (l *Logger) Error(a ...interface{})
- func (l *Logger) ErrorE(err error)
- func (l *Logger) Errorf(format string, a ...interface{})
- func (l *Logger) Fatal(a ...interface{})
- func (l *Logger) FatalE(err error)
- func (l *Logger) Fatalf(format string, a ...interface{})
- func (l *Logger) HandlerLog(w http.ResponseWriter, r *http.Request)
- func (l *Logger) HandlerLogf(w http.ResponseWriter, r *http.Request, format string, a ...interface{})
- func (l *Logger) Info(a ...interface{})
- func (l *Logger) Infof(format string, a ...interface{})
- func (l *Logger) Log(lvl LogLevel, a ...interface{})
- func (l *Logger) Notice(a ...interface{})
- func (l *Logger) Noticef(format string, a ...interface{})
- func (l *Logger) Panic(a ...interface{})
- func (l *Logger) PanicE(err error)
- func (l *Logger) Panicf(format string, a ...interface{})
- func (l *Logger) Print(a ...interface{})
- func (l *Logger) Printf(format string, a ...interface{})
- func (l *Logger) SetColor(c ColorMode)
- func (l *Logger) SetEnvironment(env Environment)
- func (l *Logger) SetEnvironmentFromString(env string)
- func (l *Logger) SetFormat(format string)
- func (l *Logger) SetFunction(name string)
- func (l *Logger) SetLogLevel(level LogLevel)
- func (l *Logger) SetModuleName(name string)
- func (l *Logger) SetOutput(out io.Writer)
- func (l *Logger) StackAsError(message string)
- func (l *Logger) StackAsFatal(message string)
- func (l *Logger) Success(a ...interface{})
- func (l *Logger) Successf(format string, a ...interface{})
- func (l *Logger) Trace(name, file string, line int)
- func (l *Logger) UseJSONForProduction()
- func (l *Logger) Warning(a ...interface{})
- func (l *Logger) WarningE(err error)
- func (l *Logger) Warningf(format string, a ...interface{})
- type Options
- type Worker
- func (w *Worker) GetEnvironment() Environment
- func (w *Worker) Log(level LogLevel, calldepth int, info *Info)
- func (w *Worker) SetEnvironment(env Environment)
- func (w *Worker) SetFormat(format string)
- func (w *Worker) SetFunction(name string)
- func (w *Worker) SetLogLevel(level LogLevel)
- func (w *Worker) SetOutput(out io.Writer)
- func (w *Worker) UseJSONForProduction()
Constants ¶
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 )
const ( Black = (iota + 30) Red Green Yellow Blue Magenta Cyan White )
Color numbers for stdout
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
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
Types ¶
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
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 ¶
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) Debugf ¶
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) Errorf ¶
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) Fatalf ¶
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) Infof ¶
Infof logs a message at Info level using the same syntax and options as fmt.Printf
func (*Logger) Log ¶
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 ¶
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) Panicf ¶
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 ¶
Printf logs a message at Info level using the same syntax and options as fmt.Printf
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
SetEnvironmentFromString is used to manually set the log environment to either development, testing or production
func (*Logger) SetFunction ¶
SetFunction sets the function name of the logger
func (*Logger) SetModuleName ¶
SetModuleName sets the name of the module being logged
func (*Logger) StackAsError ¶
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
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 ¶
Successf logs a message at Success level using the same syntax and options as fmt.Printf
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
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 ¶
EnvAsString returns the current envirnment for options as a string
type Worker ¶
Worker class, Worker is a log object used to log messages and Color specifies if colored output is to be produced
func NewWorker ¶
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) SetEnvironment ¶
func (w *Worker) SetEnvironment(env Environment)
SetEnvironment is used to manually set the log environment to either development, testing or production
func (*Worker) SetFunction ¶
SetFunction sets the function name ofr the worker
func (*Worker) UseJSONForProduction ¶
func (w *Worker) UseJSONForProduction()
UseJSONForProduction forces using JSON instead of log for production