log

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2022 License: MIT Imports: 9 Imported by: 1

README

Logger for Ottermations

This repository contains a unified logger for Ottermations.

How it works

This package manages an underlying singleton logger instance which is deemed the best for all projects and exposes an interface which will not change even if the underlying logging library changes. Details on this implementation can be found in ./logger.go

We expose 6 different types of logging functions with appropriate formatted versions (eg. SomeLogLevel() will have SomeLogLevelf() that works like Print and Printf)

Function Level Default output Use case
Print N/A stdout Program output
Trace Trace stderr Appplication logging at Trace level
Debug Debug stderr Application logging at Debug level
Info Info stderr Application logging at Info level
Warn Warning stderr Application logging at Warn level
Error Error stderr Application logging at Error level

The default log level is set to LevelInfo. To change this:

log.SetLevel(log.LevelTrace)

The default log format is set to textual (log.FormatText). To change this:

log.SetFormat(log.FormatJson)

The default log output is set to stderr so that output via Print/Printf can be piped to another application. To change this:

log.SetOutput(os.Stdout)

Other things this can do

Alerts to Telegram

This feature is for scrappy projects without a proper logging system but who wants to know if things are going down. The exposed functions are Alert and Alertf which sends an alert to the configured global AlertTarget.

To use this, first set the following environment variables:

  1. LOG_ALERT_TELEGRAM_CHAT_ID: the chat ID according to your Telegram Bot (must be numerical)
  2. LOG_ALERT_TELEGRAM_TOKEN: the API token to use with the Telegram Bot API

Then in code, use:

log.Alert("hello world")

To change where an Alert gets sent to (in future):

// for an example of a not-yet-developed Discord alert...
log.AlertTarget = log.AlertTargetDiscord

See ./alerts.go for more information

Log to a bytes.Buffer

Sometimes you might want to collate logs into a buffer before displaying it, for that, you can do so using:

var buffer bytes.Buffer
writer := bufio.NewWriter(&buffer)
log.SetOutput(writer)
// do the printing thang
writer.Flush()
fmt.Println(buffer.String())

Example

A full example can be found at ./cmd/example.

Running the following:

$ go run ./cmd/example/ > ./test-gt

Gets the following output:

INFO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stderr] message from Info                   
INFO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stderr] message from Infof                  
WARN[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stderr] message from Warn                   
WARN[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stderr] message from Warnf                  
ERRO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stderr] message from Error                  
ERRO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stderr] message from Errorf 

With this in the resulting file:

- - - - - - - - - -
default outputs to os.Stderr (filter out with appending '2>/dev/null' to invocation)
- - - - - - - - - -
[stderr] message from Print
[stderr] message from Printf
- - - - - - - - - -
output to os.Stdout (filter out with appending '1>/dev/null' to invocation)
- - - - - - - - - -
[stdout] message from Print
[stdout] message from Printf
INFO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stdout] message from Info                   
INFO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stdout] message from Infof                  
WARN[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stdout] message from Warn                   
WARN[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stdout] message from Warnf                  
ERRO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stdout] message from Error                  
ERRO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [stdout] message from Errorf                 
- - - - - - - - - -
output to bytes.Buffer (printed using fmt.Print to os.Stdout)
- - - - - - - - - -
[custom (stdout)] message from Print
[custom (stdout)] message from Printf
INFO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [custom (stdout)] message from Info          
INFO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [custom (stdout)] message from Infof         
WARN[2022-11-19 15:56:06 +0800]main.go main.writeLogs [custom (stdout)] message from Warn          
WARN[2022-11-19 15:56:06 +0800]main.go main.writeLogs [custom (stdout)] message from Warnf         
ERRO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [custom (stdout)] message from Error         
ERRO[2022-11-19 15:56:06 +0800]main.go main.writeLogs [custom (stdout)] message from Errorf

License

Code is licensed under the MIT license

Documentation

Overview

Package log is a utility module that provides logging capabilities for internal use. Logs that are emitted via this package are NOT for workload execution logs or audit trails

Index

Constants

View Source
const (
	// AlertTargetTelegram indicates that alerts should be sent to
	// Telegram
	AlertTargetTelegram alertTarget = "telegram"

	// AlertTypeError defines the 'error' level of alerts
	AlertTypeError alertType = "error"

	// AlertTypeInfo defines the 'info' level of alerts
	AlertTypeInfo alertType = "info"

	// EnvKeyAlertTelegramChatId defines the environment variable key
	// where the Telegram chat ID will be retrieved from
	EnvKeyAlertTelegramChatId = "LOG_ALERT_TELEGRAM_CHAT_ID"

	// EnvKeyAlertTelegramToken defines the environment variable key
	// where the Telegram token will be retrieved from
	EnvKeyAlertTelegramToken = "LOG_ALERT_TELEGRAM_TOKEN"
)
View Source
const (
	// TimestampYmdHMS uses format "2006-01-02 15:04:05"
	TimestampYmdHMS = "2006-01-02 15:04:05"

	// TimestampYmdHMSz uses format "2006-01-02 15:04:05 -0700"
	TimestampYmdHMSz = "2006-01-02 15:04:05 -0700"

	// TimestampMySql uses format "2006-01-02 15:04:05.999999"
	TimestampMySql = "2006-01-02 15:04:05.999999"
)

Variables

View Source
var AlertTarget = defaultAlertTarget
View Source
var Formats []Format

Formats contains a list of available formats that is accepted by us and can be useful for providing a list of valid formats in packages that consume this library

View Source
var Levels []Level

Levels defines the available levels, useful for listing the available levels in packages that consume this library

Functions

func Alert

func Alert(t alertType, message string) error

Alert executes sending of an alert

func Alertf

func Alertf(t alertType, message string, formatting ...interface{}) error

Alertf is a convenience function to execute an Alert with a formatted string

func SetFormatter

func SetFormatter(f Format)

SetFormatter sets the format of the logs

func SetLevel

func SetLevel(l Level)

SetLevel sets the level of logs to display and is an exposed interface that interacts with the underlying log library

func SetOutput

func SetOutput(output io.Writer)

SetOutput sets the output stream

Types

type Format

type Format string

Format defines the type of an accepted format

const (
	// FormatText defines the 'text' output format
	FormatText Format = "text"

	// FormatJson defines the 'json' output format
	FormatJson Format = "json"
)

type FormattedLog

type FormattedLog func(string, ...interface{})

FormatteedLog is like fmt.Printf with fancy formatting

var Printf,

	Tracef,

	Debugf,

	Infof,

	Warnf,

	Errorf FormattedLog = printf, loggerInstance.Tracef, loggerInstance.Debugf, loggerInstance.Infof, loggerInstance.Warnf, loggerInstance.Errorf

Printf writes the log to stdout with formatting

type Level

type Level uint

Level defines an accepted log level by this package

const (
	// LevelTrace defines the 'trace' level of logging
	LevelTrace Level = iota
	// LevelDebug defines the 'debug' level of logging
	LevelDebug
	// LevelInfo defines the 'info' level of logging
	LevelInfo
	// LevelWarn defines the 'warning' level of logging
	LevelWarn
	// LevelError defines the 'error' level of logging
	LevelError
)

type SimpleLog

type SimpleLog func(...interface{})

SimpleLog is like fmt.Print without any fancy formats

var Print,

	Trace,

	Debug,

	Info,

	Warn,

	Error SimpleLog = print, loggerInstance.Trace, loggerInstance.Debug, loggerInstance.Info, loggerInstance.Warn, loggerInstance.Error

Print writes the log to stdout

Directories

Path Synopsis
cmd
example command

Jump to

Keyboard shortcuts

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