log

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2023 License: MIT Imports: 15 Imported by: 1

README

AwesomeLog

Go Reference Last Release Version Go Version License

AwesomeLog is a fully compatible drop-in replacement for the standard library logger with some awesome features.

AwesomeLog let you define log levels for each logged messages as well as a PrettyPrint function to print out objects in a pretty readable format. It also adds the option to show details of the caller like file path, function name and line number.

AwesomeLog now also provides the functionality to add custom handlers for each LogLevel.

Documentation

Documentation

Quick start

The simplest way to use AwesomeLog is to just replace the standard library log with AwesomeLog:

package main

import (
log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
log.Println("Hello World!")
}

Output: 2022/02/14 09:32:44 [INFO] Hello World!

Examples

package main
import (
    log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
    log.SetLogLevel(log.VERBOSE)

    log.Print("foobar")
}
package main
import (
    log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
    log.SetLogLevel(log.VERBOSE)

    log.Println("Foobar")
}
package main
import (
    log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
    log.SetLogLevel(log.VERBOSE)

    log.Printf("Foo%s", "Bar")
}
package main
import (
    log "github.com/chris-dot-exe/AwesomeLog"
)

type foo struct {
	Foo string
	Bar string
	Foobar struct {
		Meeps []string
	}
}

func main() {
    log.SetLogLevel(log.VERBOSE)

    foo := foo{
		Foo: "Test",
		Bar: "Test",
		Foobar: struct {
    	Meeps []string
		}{[]string{"Meep", "Meep2", "Meep2.1"}},
	}

    log.PrettyPrint(foo)
}

Output:

cmdline output
Examples with Loglevel

Now the interesting part:

package main
import (
    log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
    log.SetLogLevel(log.VERBOSE)

    log.Println(log.VERBOSE, "Foobar Verbose")
    log.Println(log.DEBUG, "Foobar Debug")
    log.Println(log.INFO, "Foobar Info")
    log.Println(log.WARN, "Foobar Warning")
    log.Println(log.ERROR, "Foobar Error")
    log.Println(log.CRITICAL, "Foobar PANIC MODE! aka critical")
}

Output:

cmdline output
Show only messages to a specific level:

The priority of the log levels is as following (highest to lowest):

NONE
CRITICAL
ERROR
WARN
INFO
DEBUG
VERBOSE

If you set the log-level to info:

package main
import (
    log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
    log.SetLogLevel(log.INFO)

    log.Println(log.VERBOSE, "Foobar Verbose")
    log.Println(log.DEBUG, "Foobar Debug")
    log.Println(log.INFO, "Foobar Info")
    log.Println(log.WARN, "Foobar Warning")
    log.Println(log.ERROR, "Foobar Error")
    log.Println(log.CRITICAL, "Foobar Critical")
}

The output is reduced to the following messages:

cmdline output
Config Example
package main
import (
	log "github.com/chris-dot-exe/AwesomeLog"
)

func main() {
	cfg := log.DefaultLevelConfig()

    cfg.Debug.ShowLineNumber = false
    cfg.Debug.ShowFunctionName = true
    cfg.Debug.ShowFilePath = false

	log.SetLevelConfig(cfg)
}
Custom Handler

It is possible to add custom handler for each LogLevel.
The example below shows how a custom handler for GlitchTip/Sentry can be defined:

package main

import (
  log "github.com/chris-dot-exe/AwesomeLog"
  "github.com/getsentry/sentry-go"
  "time"
)

func main() {
  // Setup GlitchTip
  sentry.Init(sentry.ClientOptions{
    Dsn: "http://0d985cf763a34732a4839eea121c2f25@localhost:8000/1",
  })
  defer sentry.Flush(time.Second * 5)
  // Setup AwesomeLog
  log.SetDefaultLevel(log.INFO)

  // Get Default Level Config
  lvlConfig := log.DefaultLevelConfig()
  // Add custom Handler
  lvlConfig.Warn.AddHandler(GlitchContextLogger)
  lvlConfig.Debug.AddHandler(GlitchContextLogger)
  lvlConfig.Info.AddHandler(GlitchMessage)
  // Set new Level Config
  log.SetLevelConfig(lvlConfig)

  logTest()
}

func GlitchContextLogger(message log.Message) {
  sentry.ConfigureScope(func(scope *sentry.Scope) {
    scope.SetContext("caller", message.Caller)
    scope.SetTag("level", message.Level.String())
  })
  sentry.CaptureMessage(message.Message)
}

func GlitchMessage(message log.Message) {
  sentry.CaptureMessage(message.Message)
}

func logTest() {
  log.Println(log.DEBUG, "some debug message")
  log.Println(log.INFO, "some info message")
  log.Println(log.WARN, "something went wrong")
  log.Println(log.VERBOSE, "verbose message, not sent to GlitchTip")
}

In GlitchTip:

GlitchTip Details GlitchTip Details

Documentation

Overview

AwesomeLog is a fully compatible drop-in replacement for the standard library logger with some awesome features.

AwesomeLog let you define log levels for each logged messages as well as a PrettyPrint function to print out objects in a pretty readable format. It also adds the option to show details of the caller like file path, function name and line number.

AwesomeLog also provides the functionality to add custom handlers for each LogLevel.

The simplest way to use AwesomeLog is to just replace the standard library log with AwesomeLog:

package main

import  log "github.com/chris-dot-exe/AwesomeLog"

func main() {
  log.Println("Hello World!")
}

Index

Examples

Constants

View Source
const (
	ANSI_RESET             = "\u001B[0m"
	ANSI_BLACK             = "\u001B[30m"
	ANSI_WHITE             = "\u001B[37m"
	ANSI_RED_BACKGROUND    = "\u001B[41m"
	ANSI_YELLOW_BACKGROUND = "\u001B[43m"
	ANSI_BLUE_BACKGROUND   = "\u001B[44m"
	ANSI_PURPLE_BACKGROUND = "\u001B[45m"
)

ANSI color constants

Variables

This section is empty.

Functions

func Fatal

func Fatal(params ...interface{})

Fatal calls log.Fatal of the built-in log package. This function is provided only for drop-in compatibility

func Fatalf

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

Fatalf calls log.Fatalf of the built-in log package. This function is provided only for drop-in compatibility

func Fatalln

func Fatalln(params ...interface{})

Fatalln calls log.Fatalln of the built-in log package. This function is provided only for drop-in compatibility

func Panic

func Panic(params ...interface{})

Panic calls log.Panic of the built-in log package. This function is provided only for drop-in compatibility

func Panicf

func Panicf(format string, params ...interface{})

Panicf calls log.Panicf of the built-in log package. This function is provided only for drop-in compatibility

func Panicln

func Panicln(params ...interface{})

Panicln calls log.Panicln of the built-in log package. This function is provided only for drop-in compatibility

func PrettyPrint

func PrettyPrint(params ...interface{})

PrettyPrint logs a message at the defined LogLevel formatted as JSON Works only with exported fields.

Example
bar := Foo{
	Foo: "Test",
	Bar: "Test",
	Foobar: struct {
		Meeps []string
	}{[]string{"Meep", "Meep2", "Meep2.1"}},
}

PrettyPrint(INFO, bar)
Output:

2022/02/15 22:32:38 [INFO] [
 {
   "Foo": "Test",
   "Bar": "Test",
   "Foobar": {
     "Meeps": [
       "Meep",
       "Meep2",
       "Meep2.1"
     ]
   }
 }
]

func Print

func Print(params ...interface{})

Print logs a message at the defined LogLevel

Example
Print(INFO, "hello ")
Print(INFO, "world!")
Output:

2022/02/15 22:46:51 [INFO] hello
2022/02/15 22:46:51 [INFO] world!
Example (WithoutTimestamp)
ShowTimestamp(false)
Print(INFO, "hello ")
Print(INFO, "world!")
Output:

[INFO] hello [INFO] world!

func Printf

func Printf(paramsOriginal ...interface{})

Printf logs a message at the defined LogLevel and formats the message according to a format specifier

Example
Printf(DEBUG, "Hello %s!\n", "world")
Output:

2022/02/15 23:18:02 [DEBUG][main.go:main:47] Hello world!

func Println

func Println(params ...interface{})

Println logs a message at the defined LogLevel a newline is appended

Example
Println(INFO, "line 1")
Println(INFO, "line 2")
Output:

2022/02/15 22:46:51 [INFO] line 1
2022/02/15 22:46:51 [INFO] line 2
Example (WithoutTimestamp)
ShowTimestamp(false)
Println(INFO, "line 1")
Println(INFO, "line 2")
Output:

[INFO] line 1
[INFO] line 2

func SetCallerMaxDepth added in v1.0.6

func SetCallerMaxDepth(depth int)

SetCallerMaxDepth set the max depth of the callers file path

func SetDefaultLevel

func SetDefaultLevel(lvl LogLevel)

SetDefaultLevel defines which LogLevel should be used if no LogLevel is provided. This is useful if AwesomeLog is used as a drop-in replacement for the build-in log package in existing projects.

Default is INFO

Example
SetDefaultLevel(INFO)
Output:

func SetLevelConfig added in v0.10.0

func SetLevelConfig(cfg *Config)

SetLevelConfig set the config for AwesomeLog

Example
lvlConfig := DefaultLevelConfig()

lvlConfig.Debug.ShowLineNumber = false
lvlConfig.Debug.ShowFunctionName = true
lvlConfig.Debug.ShowFilePath = false

SetLevelConfig(lvlConfig)
Output:

func SetLogLevel

func SetLogLevel(lvl LogLevel)

SetLogLevel defines to which LogLevel log messages should be shown.

Default is VERBOSE

Example
SetLogLevel(WARN)
Output:

func SetLogLevelByString

func SetLogLevelByString(lvlStr string)

SetLogLevelByString defines to which LogLevel log messages should be shown based on the given string e.g. SetLogLevelByString("WARN") This is useful if the LogLevel is defined in a config file.

Example
SetLogLevelByString("WARN")
Output:

func SetTimeFormat added in v1.0.6

func SetTimeFormat(format string)

SetTimeFormat set the timeformat for log messages

Example
SetTimeFormat("2006/01/02 15:04:05.000000")
Printf(DEBUG, "Hello %s!\n", "world")
// Output 2022/02/15 23:18:02.278461 [DEBUG] Hello world!
Output:

func ShowCaller added in v0.9.6

func ShowCaller(show bool)

ShowCaller defines if the caller (function name, line number, file path) should be shown on a global level.

func ShowColors added in v0.10.0

func ShowColors(show bool)

ShowColors Defines if colored level tags should be shown in the console log.

func ShowColorsInLogs

func ShowColorsInLogs(show bool)

ShowColorsInLogs if set to true colored level tags are always active. By default, colored level tags are only active when the log is written to a terminal

func ShowTimestamp added in v0.10.0

func ShowTimestamp(show bool)

ShowTimestamp defines if the log message should be prefixed with a timestamp

func SprettyPrint added in v0.10.0

func SprettyPrint(params ...interface{}) string

func Sprint added in v0.10.0

func Sprint(params ...interface{}) string

func Sprintf added in v0.10.0

func Sprintf(paramsOriginal ...interface{}) string

func Sprintln added in v0.10.0

func Sprintln(params ...interface{}) string

Types

type Caller added in v1.0.2

type Caller struct {
	Path         string
	FunctionName string
	LineNumber   int
}

Caller contains the Caller information file path, function name and line number

func (Caller) ToMap added in v1.0.6

func (c Caller) ToMap() map[string]interface{}

type Config added in v0.10.0

type Config struct {
	Verbose  LevelConfig
	Debug    LevelConfig
	Info     LevelConfig
	Warn     LevelConfig
	Error    LevelConfig
	Critical LevelConfig
}

Config represents the config for all LogLevels

func DefaultLevelConfig added in v0.10.0

func DefaultLevelConfig() *Config

DefaultLevelConfig return the default level config for AwesomeLog

type Handler added in v1.0.2

type Handler func(message Message)

type LevelConfig added in v0.10.0

type LevelConfig struct {
	ShowLineNumber   bool
	ShowFunctionName bool
	ShowFilePath     bool
	Handlers         []Handler
}

LevelConfig represents the configuration for each LogLevel

func (*LevelConfig) AddHandler added in v1.0.2

func (c *LevelConfig) AddHandler(handler Handler)

AddHandler adds a custom Handler to the existing handlers of the LogLevel

func (*LevelConfig) SetHandlers added in v1.0.2

func (c *LevelConfig) SetHandlers(handler []Handler)

SetHandlers sets custom handlers for the LogLevel. SetHandlers overrides the existing handler

type LogLevel

type LogLevel uint
const (
	NONE     LogLevel = 0
	CRITICAL LogLevel = 10
	ERROR    LogLevel = 20
	WARN     LogLevel = 30
	INFO     LogLevel = 50
	DEBUG    LogLevel = 70
	VERBOSE  LogLevel = 100
)

func (*LogLevel) Color added in v0.10.0

func (t *LogLevel) Color() string

Color returns the defined color of the LogLevel

func (*LogLevel) String added in v0.10.0

func (t *LogLevel) String() string

String returns the LogLevel name as string

type Message added in v1.0.2

type Message struct {
	Time    time.Time
	Level   LogLevel
	Caller  Caller
	Message string
}

Message is the object which is passed to every handler function. Message contains the LogLevel, the Caller object and the message

Directories

Path Synopsis
test

Jump to

Keyboard shortcuts

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