slog

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2020 License: Apache-2.0 Imports: 12 Imported by: 40

README

SLog - Golang Super Simple Logging

Apache License Coverage Status Build Status

Usage:

package main

import (
    "github.com/quan-to/slog"
    "time"
)

var log = slog.Scope("MAIN")


func Call0(i slog.Instance, arg0 string) {
    l := i.SubScope("Call0").WithFields(map[string]interface{}{
        "arg0": arg0,
    })
    l.Await("Doing some work")
    time.Sleep(time.Second)
    l.Done("Finished some work")
    l.Note("Not sure what I'm doing...")
    l.Info("Calling Call1")
    Call1(l, "call1arg")
    l.Done("Exiting")
}

func Call1(i slog.Instance, huebr string) {
    l := i.SubScope("Call1").WithFields(map[string]interface{}{
        "huebr": huebr,
    })
    l.Info("Calling Call2")
    Call2(l, "abcde")
    l.Warn("Call 1 finished")
}

func Call2(i slog.Instance, pop string) {
    l := i.SubScope("Call2").WithFields(map[string]interface{}{
        "pop": pop,
    })

    l.IO("Doing some IO")
    l.Error("I'm useless. Please fix-me")
}

func main() {
    slog.SetScopeLength(40) // Expand Scope pad length

    log = log.Tag("REQ001") // Tag current as REQ001

    log.Info("Starting program")

    Call0(log, "MyArg0")

    Call1(log, "Call1Arg")
    Call2(log, "Call2Arg")
}

Output:

Sample Output

Log Pattern

There are 2 types of outputs: Pipe Delimited Text (default) and JSON.
To change the type of output, call the function SetLogFormat:

slog.SetLogFormat(JSON)
Pipe Delimited Text

The slog output is expected to be like this:

2019-09-16T15:35:52-03:00 | I | IO    | REQ001 | MAIN > Call0 > Call1 > Call2             | test.go:38 | Doing some IO  | {"arg0":"MyArg0","huebr":"call1arg","pop":"abcde"}

There are some fields that are optional (like filename/line number) but it should always follow the same pattern:

DATETIME | LEVEL | OPERATION | TAG | SCOPE | [FILENAME:LINE NUMBER] | MESSAGE | LOG FIELDS
  • DATETIME => An ISO Datetime when the log is displayed
  • LEVEL => The level of the log line
    • I => INFO - Shows an information usually to track what's happening inside an application
    • W => WARN - Shows an warning regarding something that went in a way that might require some attention
    • E => ERROR - Shows an application error that can be expected or not
    • D => DEBUG - Shows some debug information to help tracking issues
    • F => FATAL - Shows an error that will quit the application in that point
  • TAG => Line log tag. Use this for tracking related log lines. For example with a HTTP Request ID
  • SCOPE => The scope of the current log. Use this to trace the chain of calls inside the application. For example in a context change
  • FILENAME: LINE NUMBER => OPTIONAL When ShowLines is enabled, it will show the filename and the line number of the caller of the slog library. Use this on debug mode to see which piece of code called the log library. Disabled by default
  • MESSAGE => The message
  • LOG FIELDS => When an instance is created using WithFields call, the fields will be serialized to either JSON or Key-Value depending on the configuration of the log instance. Defaults to JSON
JSON

The output is expected to be in this format:

{
  "level":"info",
  "op":"MSG",
  "msg":"Processing rule 123",
  "scope":"PriceCalc",
  "tag":"RULE_ENGINE",
  "time":"2020-02-07T15:36:20-03:00",
  "customField01":"123"
}

The fields are the same as from Pipe Delimited Text and work the same way, except that the Key-Value option is not available for the LOG FIELDS.

Operations Usage

The library implements the concept of operation type. This describes which type of operation the log line represents.

  • IO => Anytime you do a I/O Operation such as Database or File Read/Write
  • AWAIT => Anytime you will do a asynchronous operation that will block the flow
  • DONE => After any AWAIT operation you should always use a DONE to log that the operation that did the AWAIT log line has finished.
  • NOTE => Also know as Verbose, that operation is used when you're just letting the log reader some note about the operation
  • MSG => Common messages such like normal information (which does not fit in other operations)

There are some syntax sugars to make easy to use Log Levels with Log Operations together:

  • Warning Messages
    • WarnDone => Same as log.Operation(DONE).Warn(message)
    • WarnNote => Same as log.Operation(NOTE).Warn(message)
    • WarnAwait => Same as log.Operation(AWAIT).Warn(message)
    • WarnSuccess => Same as log.Operation(DONE).Warn(message)
    • WarnIO => Same as log.Operation(IO).Warn(message)
  • Error Messages
    • ErrorDone => Same as log.Operation(DONE).Error(message)
    • ErrorNote => Same as log.Operation(NOTE).Error(message)
    • ErrorAwait => Same as log.Operation(AWAIT).Error(message)
    • ErrorSuccess => Same as log.Operation(DONE).Error(message)
    • ErrorIO => Same as log.Operation(IO).Error(message)
  • Debug Messages
    • DebugDone => Same as log.Operation(DONE).Debug(message)
    • DebugNote => Same as log.Operation(NOTE).Debug(message)
    • DebugAwait => Same as log.Operation(AWAIT).Debug(message)
    • DebugSuccess => Same as log.Operation(DONE).Debug(message)
    • DebugIO => Same as log.Operation(IO).Debug(message)

Use these syntax sugars whenever is possible, instead of calling Operation(X).Level directly.

Multiline Logs

If a multiline log is displayed, the library will correctly ident all the messages:

2019-09-16T15:39:42-03:00 | I | MSG   | REQ001 | MAIN  | Multiline call
                                                         Thats the second line
                                                         Thats the third line  | {}
Use Patterns
  • After calling a Await, you should always call a Done or Success
  • Don't add extensive fields to WithFields as it will pollute the log
  • Avoid multiline logs as this make parsing hard.
  • Avoid using pipes | in your log message or fields
  • Instead of Operation(AWAIT).Warn use WarnAwait
  • Use Tag to indentify calls in the same flow (for example on a HTTP Request)
  • All LogInstance calls returns a new LogInstance with the modified data. It will never change it's parent data making it completely immutable.

Documentation

Index

Constants

View Source
const (
	MSG   LogOperation = "MSG"
	IO                 = "IO"
	AWAIT              = "AWAIT"
	DONE               = "DONE"
	NOTE               = "NOTE"
)
View Source
const (
	// INFO represents a Information Log Level (or verbose)
	INFO LogLevel = "I"

	// WARN represents a Warning Log Level
	WARN = "W"

	// ERROR represents an error message
	ERROR = "E"

	// FATAL represents an fatal message
	FATAL = "F"

	// DEBUG represents an debug message
	DEBUG = "D"
)
View Source
const LineBreak = "\n"

Variables

This section is empty.

Functions

func DebugEnabled

func DebugEnabled() bool

DebugEnabled returns if the DEBUG level messages are currently enabled

func ErrorEnabled

func ErrorEnabled() bool

ErrorEnabled returns if the ERROR level messages are currently enabled

func Fatal

func Fatal(str interface{}, v ...interface{})

Fatal logs out a message in ERROR level and closes the program

func InfoEnabled

func InfoEnabled() bool

InfoEnabled returns if the INFO level messages are currently enabled

func SetDebug

func SetDebug(enabled bool)

SetDebug globally sets if the DEBUG level messages will be shown. Affects all instances

func SetDefaultOutput

func SetDefaultOutput(o io.Writer)

SetDefaultOutput sets the Global Default Output I/O and for every new instance created by Scope function

func SetError

func SetError(enabled bool)

SetError globally sets if the ERROR level messages will be shown. Affects all instances

func SetFieldRepresentation

func SetFieldRepresentation(representationType FieldRepresentationType)

SetFieldRepresentation globally sets if the representation of log fields. Affects all instances

func SetInfo

func SetInfo(enabled bool)

SetInfo globally sets if the INFO level messages will be shown. Affects all instances

func SetLogFormat

func SetLogFormat(f Format)

SetLogFormat globally sets the logging format. Affects all instances

func SetScopeLength

func SetScopeLength(length int)

SetScopeLength sets the scope field length (adds left pad when nescessary) - Affects globally all SLog Instances

func SetShowLines

func SetShowLines(enabled bool)

SetShowLines globally sets if the filename and line of the caller function will be shown. Affects all instances

func SetTestMode

func SetTestMode()

SetTestMode sets the SLog Instances to test mode a.k.a. all logs disabled. Equivalent to set all levels visibility to false

func SetWarning

func SetWarning(enabled bool)

SetWarning globally sets if the WARN level messages will be shown. Affects all instances

func ShowLinesEnabled

func ShowLinesEnabled() bool

ShowLinesEnabled returns if the show filename and line from called function is currently enabled

func UnsetTestMode

func UnsetTestMode()

UnsetTestMode sets the SLog Instances to default mode a.k.a. all logs enabled. Equivalent to set all levels visibility to true

func WarningEnabled

func WarningEnabled() bool

WarningEnabled returns if the WARN level messages are currently enabled

Types

type FieldRepresentationType

type FieldRepresentationType int

FieldRepresentationType specifies which log instance fields formatting should be used

const (
	// NoFields disables the representation of the log instance fields
	NoFields FieldRepresentationType = iota
	// JSONFields enables the representation of log instance fields and formats them as a json string
	JSONFields
	// KeyValueFields enables the representation of log instance fields and formats them as a comma separated key=value fields
	KeyValueFields
)

type Format

type Format string

Format specifies the logging format (could be pipe separated, JSON, ...)

const (
	// JSON specifies to log in JSON format
	JSON Format = "json"
	// PIPE specifies to log in Pipe Delimited Text format
	PIPE Format = "pipe"
)

func ToFormat

func ToFormat(s string) Format

ToFormat converts a string to its corresponding Format type

type Instance

type Instance interface {
	// Scope returns a new instance with the specified root scope (parent scope is discarded)
	Scope(string) Instance
	// SubScope returns a new instance with the specified scope appended to parent scope
	SubScope(string) Instance
	// WithCustomWriter returns a new instance with the specified custom output
	WithCustomWriter(io.Writer) Instance
	// WithFields returns a new instance with the parent fields plus the current fields. If key collision happens, the value specified in fields argument will be used.
	WithFields(map[string]interface{}) Instance
	// Tag returns a new instance with the specified tag.
	Tag(string) Instance
	// Operation returns a new instance with the specified operation.
	Operation(LogOperation) Instance

	// LogNoFormat prints a log string without any ANSI formatting
	LogNoFormat(interface{}, ...interface{}) Instance

	// Info logs out a message in INFO level
	Info(str interface{}, v ...interface{}) Instance
	// Debug logs out a message in DEBUG level
	Debug(str interface{}, v ...interface{}) Instance
	// Warn logs out a message in WARN level
	Warn(str interface{}, v ...interface{}) Instance
	// Error logs out a message in ERROR level
	Error(str interface{}, v ...interface{}) Instance
	// Fatal logs out a message in ERROR level and closes the program
	Fatal(str interface{}, v ...interface{})

	// Note logs out a message in INFO level and with Operation NOTE. Returns an instance of operation NOTE
	Note(interface{}, ...interface{}) Instance
	// Await logs out a message in INFO level and with Operation AWAIT. Returns an instance of operation AWAIT
	Await(interface{}, ...interface{}) Instance
	// Done logs out a message in INFO level and with Operation DONE. Returns an instance of operation DONE
	Done(interface{}, ...interface{}) Instance
	// Success logs out a message in INFO level and with Operation DONE. Returns an instance of operation DONE
	Success(interface{}, ...interface{}) Instance
	// IO logs out a message in INFO level and with Operation IO. Returns an instance of operation IO
	IO(interface{}, ...interface{}) Instance
	// Log is equivalent of calling Info. It logs out a message in INFO level
	Log(interface{}, ...interface{}) Instance

	WarnDone(interface{}, ...interface{}) Instance
	WarnNote(interface{}, ...interface{}) Instance
	WarnAwait(interface{}, ...interface{}) Instance
	WarnSuccess(interface{}, ...interface{}) Instance
	WarnIO(interface{}, ...interface{}) Instance

	ErrorDone(interface{}, ...interface{}) Instance
	ErrorNote(interface{}, ...interface{}) Instance
	ErrorAwait(interface{}, ...interface{}) Instance
	ErrorSuccess(interface{}, ...interface{}) Instance
	ErrorIO(interface{}, ...interface{}) Instance

	DebugDone(interface{}, ...interface{}) Instance
	DebugNote(interface{}, ...interface{}) Instance
	DebugAwait(interface{}, ...interface{}) Instance
	DebugSuccess(interface{}, ...interface{}) Instance
	DebugIO(interface{}, ...interface{}) Instance
}

Instance is a interface to a compatible SLog Logging Instance

func Debug

func Debug(str interface{}, v ...interface{}) Instance

Debug logs out a message in DEBUG level

func Error

func Error(str interface{}, v ...interface{}) Instance

Error logs out a message in ERROR level

func Info

func Info(str interface{}, v ...interface{}) Instance

Info logs out a message in INFO level

func Log

func Log(str interface{}, v ...interface{}) Instance

Log is equivalent of calling Info. It logs out a message in INFO level

func LogNoFormat

func LogNoFormat(str interface{}, v ...interface{}) Instance

LogNoFormat prints a log string without any ANSI formatting

func Scope

func Scope(scope string) Instance

Scope creates a new slog Instance with the specified root scope

func Warn

func Warn(str interface{}, v ...interface{}) Instance

Warn logs out a message in WARN level

type LogLevel

type LogLevel string

LogLevel type specifies the level of log to be used

type LogOperation

type LogOperation string

type StringCast

type StringCast interface {
	String() string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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