noodlog

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2023 License: Apache-2.0 Imports: 9 Imported by: 1

README

Noodlog

License Mentioned in Awesome Go CodeFactor Go Report Card Maintenance made-with-Go codecov Open Source Love svg1

alt text

Summary

Noodlog is a Golang JSON parametrized and highly configurable logging library.

It allows you to:

  • print go structs as JSON messages;
  • print JSON strings and raw strings messages as pure JSONs;
  • obscure some sensitive params from your logging;
  • chain objects or strings in your logs;
  • apply string templates to your logs;
  • choose to trace the caller file and function and fine tune the settings;
  • apply pretty printing or not;
  • apply colors to your logging;
  • customize colors per log level.

Import

go get github.com/gyozatech/noodlog

Usage

Let's assume you have Go 1.16+ istalled on your computer. Execute the following:

$ mkdir example && cd example
$ go mod init example
$ go get github.com/gyozatech/noodlog
$ touch main.go

Open main.go and paste the following code:

package main

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger().SetConfigs(
      noodlog.Configs{
         LogLevel: noodlog.LevelTrace,
         JSONPrettyPrint: noodlog.Enable,
         TraceCaller: noodlog.Enable,
         Colors: noodlog.Enable,
         CustomColors: &noodlog.CustomColors{ Trace: noodlog.Cyan },
         ObscureSensitiveData: noodlog.Enable,
         SensitiveParams: []string{"password"},
      },
    )
}

func main() {
    // simple string message (with custom color)
    log.Trace("Hello world!")
    
    // chaining elements
    log.Info("You've reached", 3, "login attemps")
    
    // using string formatting
    log.Warn("You have %d attempts left", 2)
    
    // logging a struct with a JSON
    log.Error(struct{Code int; Error string}{500, "Generic Error"})
    
    // logging a raw JSON string with a JSON (with obscuring "password")
    log.Info(`{"username": "gyozatech", "password": "Gy0zApAssw0rd"}`)
    
    // logging a JSON string with a JSON (with obscuring "password")
    log.Info("{\"username\": \"nooduser\", \"password\": \"N0oDPasSw0rD\"}")
}

Running this example with:

$ go run main.go

You'll get the following output:

alt text

Settings

Noodlog allows you to customize the logs through various settings. You can use various facility functions or the SetConfigs function which wraps all the configs together.


LogLevel

To set the logging level, after importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

you can use the facility method:

log.LogLevel("warn")

or the SetConfigs function:

log.SetConfigs(
    noodlog.Configs{
        LogLevel: noodlog.LevelWarn,
    },
)

log.LevelWarn is a pre-built pointer to the string "warn".

The default log level is info.


JSON Pretty Printing

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

To enable pretty printing of the JSON logs you can use:

log.EnableJSONPrettyPrint()

or

log.SetConfigs(
    noodlog.Configs{
       JSONPrettyPrint: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

to disable pretty printing you can use:

log.DisableJSONPrettyPrint()

or

log.SetConfigs(
    noodlog.Configs{
       JSONPrettyPrint: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.


Colors

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

to enable colors in JSON logs you can use:

log.EnableColors()

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

To disable colors you can use:

log.DisableColors()

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.

Color

The basic way to use a custom color is declaring using a pointer of a string representing the color.
log.Cyan, log.Green, log.Default, log.Yellow, log.Purple, log.Red, log.Blue are pre-build pointers to the strings "cyan", "green", "default", "yellow", "purple", "red", "blue".

For instance, you can customize trace color by:

log.SetTraceColor(noodlog.Cyan)

A more detailed explanation of each log level is available later into this section.

Composition of a color

Color can be composed with text color and background color. For each level it can be composed using a string or a true color notation.

Trivial usage is creating a new color like:

log.NewColor(noodlog.Red)

It results a red text on default background

Adding a background color can be done through:

log.NewColor(noodlog.Red).Background(noodlog.Cyan)

In this scenario it prints red text on cyan background

A third option is to edit just background color using default text color:

log.Background(noodlog.Cyan)

A list of pre-built pointer of a string is [here](#Composition of a color).

Library provides also more customization through the usage of true color notation (RGB value). Before the usage of this notation, please consider if your terminal supports truecolor. For instance if you execute (printf required):

printf '\033[38;2;255;0;0mHello World\033[0m'

a red text "Hello World" should be displayed on the screen

In this way a wider set of color is available for logging, besides of the previous way it can be created a color as:

log.NewColorRGB(255,0,0).BackgroundRGB(0,0,255)

Where a red text (255 for red, 0 the others) is showed on blue background (255 for blue, 0 for others).

As in the previous scenario, NewColorRGB and BackgroundRGB hasn't to be executed combined.

Color can be used to set color of Trace log, by typing:

log.SetTraceColor(noodlog.NewColorRGB(255,0,0).BackgroundRGB(0,0,255))

You can customize the single colors (for log level) by using:

log.SetTraceColor(noodlog.Cyan)
log.SetDebugColor(noodlog.NewColorRGB(255,255,0))
log.SetInfoColor(noodlog.NewColor(noodlog.Red).Background(noodlog.Cyan))
log.SetWarnColor(noodlog.NewColor(noodlog.Green).BackgroundRGB(0,255,255))
log.SetErrorColor(noodlog.NewColorRGB(128,255,0).Background(noodlog.Purple))

or

log.SetConfigs(
    noodlog.Configs{
        Colors: noodlog.Enable,
        CustomColors: &noodlog.CustomColors{ 
            Trace: noodlog.Cyan, 
            Debug: noodlog.NewColorRGB(255,255,0),
            Info:  noodlog.NewColor(noodlog.Red).Background(noodlog.Cyan),
            Warn:  noodlog.NewColor(noodlog.Green).BackgroundRGB(0,255,255),
            Error: noodlog.NewColorRGB(128,255,0).Background(noodlog.Purple),    
        },
    },
)

Here we highlight all the different combination available to customize colors.

When enabled, the default colors are:

  • trace: "default"
  • info: "default"
  • debug: "green"
  • warn: "yellow"
  • error: "red"

Trace the caller

Noodles allows you to print the file and the function which are calling the log functions.

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

to enable the trace caller you can use:

log.EnableTraceCaller()

or

log.SetConfigs(
    noodlog.Configs{
        TraceCaller: noodlog.Enable,
    },
)

noodlog.Enable is a pre-built pointer to the bool true.

To disable it:

log.DisableTraceCaller()

or

log.SetConfigs(
    noodlog.Configs{
        TraceCaller: noodlog.Disable,
    },
)

noodlog.Disable is a pre-built pointer to the bool false.

The default value is false.

Important: if you want to import noodlog only in one package of your project (in order to configure it once) and wraps the logging functions you can use the EnableSinglePointTracing to trace file and function the real caller and not of your logging package.

For example:

main.go

package main

import (
   log "example/logging"
)

func main() {
   // main.main real caller we want to track 
   log.Info("Hello folks!")
}

logging/logger.go

package logging

import (
    "github.com/gyozatech/noodlog"
)

var l *noodlog.Logger

func init() {
    l = noodlog.NewLogger()
    // configure logger once
    l.SetConfig(
        noodlog.Configs{
         TraceCaller: noodlog.Enable,
         SinglePointTracing: noodlog.Enable,
      },
    )
}

// wrapper function
func Info(message ...interface{}) {
    // if we wouldn't enable SinglePointTracing
    // logger.Info would have been considered the caller to be tracked
    l.Info(message...)
}

Sensitive params

Noodlog gives you the possibility to enable the obscuration of sensitive params when recognized in the JSON structures (not in the simple strings that you compose).

After importing the library with:

import (
    "github.com/gyozatech/noodlog"
)

var log *noodlog.Logger

func init() {
   log = noodlog.NewLogger()
}

You can enable the sensitive params obscuration with the facility methods:

log.EnableObscureSensitiveData([]string{"param1", "param2", "param3"})

or with the SetConfig function:

log.SetConfigs(
    noodlog.Configs{
        ObscureSensitiveData: noodlog.Enable,
        SensitiveParams: []string{"param1", "param2", "param3"},
    },
)

Where noodlog.Enable is a pre-built pointer to the bool true.

To disable the sensitive params obscuration you can set:

log.DisableObscureSensitiveData()

or

log.SetConfigs(
    noodlog.Configs{
        ObscureSensitiveData: noodlog.Disable,
    },
)

Where noodlog.Disable is a pre-built pointer to the bool false.

The default value for the obscuration is false.


Contribute to the project

If you want to contribute to the project follow the following guidelines. Any form of contribution is encouraged!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Blue = pointerOfString(blueColor)

Blue pointer for the CustomColors struct

View Source
var Cyan = pointerOfString(cyanColor)

Cyan pointer for the CustomColors struct

View Source
var Default = pointerOfString(defaultColor)

Default pointer for the CustomColors struct

View Source
var Disable = pointerOfBool(false)

Disable pointer for the Config struct

View Source
var Enable = pointerOfBool(true)

Enable pointer for the Config struct

View Source
var Green = pointerOfString(greenColor)

Green pointer for the CustomColors struct

View Source
var LevelDebug = pointerOfString(debugLabel)

LevelDebug pointer for the Config struct

View Source
var LevelError = pointerOfString(errorLabel)

LevelError pointer for the Config struct

View Source
var LevelInfo = pointerOfString(infoLabel)

LevelInfo pointer for the Config struct

View Source
var LevelTrace = pointerOfString(traceLabel)

LevelTrace pointer for the Config struct

View Source
var LevelWarn = pointerOfString(warnLabel)

LevelWarn pointer for the Config struct

View Source
var Purple = pointerOfString(purpleColor)

Purple pointer for the CustomColors struct

View Source
var Red = pointerOfString(redColor)

Red pointer for the CustomColors struct

View Source
var Yellow = pointerOfString(yellowColor)

Yellow pointer for the CustomColors struct

Functions

This section is empty.

Types

type Color

type Color struct {
	Code *string
}

func Background

func Background(color *string) Color

Background set the background using a string as identifiers

func NewColor

func NewColor(color *string) Color

NewColor set the color of the text using a string as identifiers

func NewColorRGB

func NewColorRGB(red int, green int, blue int) Color

NewColorRGB set the color of the text using RGB Notations

func (Color) Background

func (c Color) Background(color *string) Color

From a given Color it set the background using a string as identifier

func (Color) BackgroundRGB

func (c Color) BackgroundRGB(red int, green int, blue int) Color

From a given Color it set the background using RGB Notations

type Configs

type Configs struct {
	LogLevel             *string
	LogWriter            io.Writer
	JSONPrettyPrint      *bool
	TraceCaller          *bool
	SinglePointTracing   *bool
	Colors               *bool
	CustomColors         *CustomColors
	ObscureSensitiveData *bool
	SensitiveParams      []string
}

Configs struct contains all possible configs for noodlog

type CustomColors

type CustomColors struct {
	Trace interface{}
	Debug interface{}
	Info  interface{}
	Warn  interface{}
	Error interface{}
}

CustomColors struct is used to specify the custom colors for the various log levels

type Logger

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

Logger represent the logger object

func NewLogger

func NewLogger() *Logger

NewLogger func is the default constructor of a Logger

func (*Logger) Debug

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

Debug function prints a log with debug log level

func (*Logger) DisableColors

func (l *Logger) DisableColors() *Logger

DisableColors function let you disable colored logs for a specified logger

func (*Logger) DisableJSONPrettyPrint

func (l *Logger) DisableJSONPrettyPrint() *Logger

DisableJSONPrettyPrint func let you disable JSON pretty printing for the specified logger instance

func (*Logger) DisableObscureSensitiveData

func (l *Logger) DisableObscureSensitiveData() *Logger

DisableObscureSensitiveData disables sensitive data obscuration from json logs for a given logger instance

func (*Logger) DisableSinglePointTracing

func (l *Logger) DisableSinglePointTracing() *Logger

DisableSinglePointTracing function trace function and filename of the directl caller

func (*Logger) DisableTraceCaller

func (l *Logger) DisableTraceCaller() *Logger

DisableTraceCaller disables the tracing of the caller for the specified logger instance

func (*Logger) EnableColors

func (l *Logger) EnableColors() *Logger

EnableColors function let you enable colored logs for a specified logger

func (*Logger) EnableJSONPrettyPrint

func (l *Logger) EnableJSONPrettyPrint() *Logger

EnableJSONPrettyPrint func let you enable JSON pretty printing for the specified logger instance

func (*Logger) EnableObscureSensitiveData

func (l *Logger) EnableObscureSensitiveData(params []string) *Logger

EnableObscureSensitiveData enables sensitive data obscuration from json logs for a given logger instance

func (*Logger) EnableSinglePointTracing

func (l *Logger) EnableSinglePointTracing() *Logger

EnableSinglePointTracing function enables tracing the caller when setting the logger in a single package for the whole project and recalling the logging for the project from that single point for the specified logger instance

func (*Logger) EnableTraceCaller

func (l *Logger) EnableTraceCaller() *Logger

EnableTraceCaller enables the tracing of the caller for the specified logger instance

func (*Logger) Error

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

Error function prints a log with error log level

func (*Logger) Fatal

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

Fatal function prints a log with fatal log level

func (*Logger) Info

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

Info function prints a log with info log level

func (*Logger) Level

func (l *Logger) Level(level string) *Logger

Level func let you establish the log level for a specified logger instance

func (*Logger) LogWriter

func (l *Logger) LogWriter(w io.Writer) *Logger

LogWriter function let you define a logWriter (os.Stdout, a file, a buffer etc.)

func (*Logger) Panic

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

Panic function prints a log with panic log level

func (*Logger) SetConfigs

func (l *Logger) SetConfigs(configs Configs) *Logger

SetConfigs function allows you to rewrite all the configs at once

func (*Logger) SetCustomColors

func (l *Logger) SetCustomColors(colors CustomColors) *Logger

SetCustomColors overrides defaultColor when custom color is passed into CustomColor configs

func (*Logger) SetDebugColor

func (l *Logger) SetDebugColor(color Color)

SetDebugColor overrides the debug level log color with the one specified in input

func (*Logger) SetErrorColor

func (l *Logger) SetErrorColor(color Color)

SetErrorColor overrides the error level log color with the one specified in input

func (*Logger) SetInfoColor

func (l *Logger) SetInfoColor(color Color)

SetInfoColor overrides the info level log color with the one specified in input

func (*Logger) SetSensitiveParams

func (l *Logger) SetSensitiveParams(params []string) *Logger

SetSensitiveParams sets sensitive data obscuration from json logs

func (*Logger) SetTraceColor

func (l *Logger) SetTraceColor(color Color)

SetTraceColor overrides the trace level log color with the one specified in input

func (*Logger) SetWarnColor

func (l *Logger) SetWarnColor(color Color)

SetWarnColor overrides the warn level log color with the one specified in input

func (*Logger) Trace

func (l *Logger) Trace(message ...interface{})

Trace function prints a log with trace log level

func (*Logger) Warn

func (l *Logger) Warn(message ...interface{})

Warn function prints a log with warn log level

Jump to

Keyboard shortcuts

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