log

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2022 License: MIT Imports: 2 Imported by: 0

README

Log Package

log-go "spin-off" logger with its API closer to the Go standard library package.

Go Reference license build

Usage

Example Go code

import (
	"fmt"

	"github.com/roninzo/log"
	"github.com/roninzo/log/impl/hclog"
	"github.com/roninzo/log/impl/logrus"
	"github.com/roninzo/log/impl/std"
	"github.com/roninzo/log/impl/zap"
)

type Foo struct {
	Logger log.Logger
}

func (f *Foo) DoSomething() {
	f.Logger.Info("Hello Logging")
	f.Logger.Info("Logging supports key-value pairs", log.Map{"foo": "bar"})
}

func main() {

	// Using the default Logger
	log.Info("Hello")
	log.Error("World")

	// Create a logrus logger with default configuration that uses the log
	// interface. Note, logrus can be setup with default settings or setup with
	// custom settings using a second constructor.
	lgrs := logrus.NewStandard()

	// Set logrus as the global logger
	log.Current = lgrs

	// Logrus is now used globally for logging
	log.Warn("Warning through logrus")

	f1 := Foo{
		Logger: lgrs,
	}

	// Logging in DoSomething will use the set logger which is logrus
	f1.DoSomething()

	f2 := Foo{
		// The log package uses the global logger from the standard library log
		// package. A custom standard library logger can be used with the
		// github.com/roninzo/log/impl/std package.
		Logger: log.NewStandard(),
	}

	// Logging in DoSomething will the logger from the standard library
	f2.DoSomething()

	// Need to detect the logger being used? You can check for the type.
	switch log.Current.(type) {
	case *log.Std:
		fmt.Println("The default logger")
	case *std.Logger:
		fmt.Println("The default logger")
	case *logrus.Logger:
		fmt.Printf("Logrus is used for logging")
	case *zap.Logger:
		fmt.Printf("Zap is used for logging")
	case *hclog.Logger:
		fmt.Printf("HashiCorp is used for logging")
	default:
		fmt.Printf("Something else that implements the interface")
	}
}

Output

2022/04/20 13:06:06 [INFO]  Hello
2022/04/20 13:06:06 [ERROR] World
time="2022-04-20T13:06:06+02:00" level=warning msg="Warning through logrus"
time="2022-04-20T13:06:06+02:00" level=info msg="Hello Logging"
time="2022-04-20T13:06:06+02:00" level=info msg="Logging supports key-value pairs" foo=bar
2022/04/20 13:06:06 [INFO]  Hello Logging
2022/04/20 13:06:06 [INFO]  Logging supports key-value pairs [foo=bar]
Logrus is used for logging

Interface

Exported logger interface

type Logger interface {
	Prefix(...string) string          // Prefix returns current logger name. With a prefix argument, the current logger's name is set to it.
	Level(...levels.Type) levels.Type // Level returns current logging level. With a level argument, the current logger's level is set to it.
	Trace(...interface{})             // Trace logs a message at the Trace level.
	Debug(...interface{})             // Debug logs a message at the Debug level.
	Info(...interface{})              // Info logs a message at the Info level.
	Warn(...interface{})              // Warn logs a message at the Warn level.
	Error(...interface{})             // Error logs a message at the Error level.
	Panic(...interface{})             // Panic logs a message at the Panic level and panics.
	Fatal(...interface{})             // Fatal logs a message at the Fatal level and exists the application.
	Tracef(string, ...interface{})    // Tracef formats a message according to a format specifier and logs the message at the Trace level.
	Debugf(string, ...interface{})    // Debugf formats a message according to a format specifier and logs the message at the Debug level.
	Infof(string, ...interface{})     // Infof formats a message according to a format specifier and logs the message at the Info level.
	Warnf(string, ...interface{})     // Warnf formats a message according to a format specifier and logs the message at the Warning level.
	Errorf(string, ...interface{})    // Errorf formats a message according to a format specifier and logs the message at the Error level.
	Panicf(string, ...interface{})    // Panicf formats a message according to a format specifier and logs the message at the Panic level and then panics.
	Fatalf(string, ...interface{})    // Fatalf formats a message according to a format specifier and logs the message at the Fatal level and exits the application.
}

Implicit logger interface

Methods cannot be declared as part of the exported interface, but are available for all implementations.

type Logger interface {
	Named(string) Logger                   // Create a new sub-Logger with a name descending from the current name. This is used to create a subsystem specific Logger.
	WithLevel(levels.Type) Logger          // Chainable level setter.
	WithLevelFromDebug(bool) Logger        // Chainable level setter from debug boolean value.
	Options(...func(Logger) Logger) Logger // Custom chainable setter functions.
}

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/roninzo/log"
	"github.com/roninzo/log/impl/hclog"
	"github.com/roninzo/log/impl/logrus"
	"github.com/roninzo/log/impl/std"
	"github.com/roninzo/log/impl/zap"
)

type Foo struct {
	Logger log.Logger
}

func (f *Foo) DoSomething() {
	f.Logger.Info("Hello Logging")
	f.Logger.Info("Logging supports key-value pairs", log.Map{"foo": "bar"})
}

func main() {

	// Using the default Logger
	log.Info("Hello")
	log.Error("World")

	// Create a logrus logger with default configuration that uses the log
	// interface. Note, logrus can be setup with default settings or setup with
	// custom settings using a second constructor.
	lgrs := logrus.NewStandard()

	// Set logrus as the global logger
	log.Current = lgrs

	// Logrus is now used globally for logging
	log.Warn("Warning through logrus")

	f1 := Foo{
		Logger: lgrs,
	}

	// Logging in DoSomething will use the set logger which is logrus
	f1.DoSomething()

	f2 := Foo{
		// The log package uses the global logger from the standard library log
		// package. A custom standard library logger can be used with the
		// github.com/roninzo/log/impl/std package.
		Logger: log.NewStandard(),
	}

	// Logging in DoSomething will the logger from the standard library
	f2.DoSomething()

	// Need to detect the logger being used? You can check for the type.
	switch log.Current.(type) {
	case *log.Std:
		fmt.Println("The default logger")
	case *std.Logger:
		fmt.Println("The default logger")
	case *logrus.Logger:
		fmt.Printf("Logrus is used for logging")
	case *zap.Logger:
		fmt.Printf("Zap is used for logging")
	case *hclog.Logger:
		fmt.Printf("HashiCorp is used for logging")
	default:
		fmt.Printf("Something else that implements the interface")
	}
}
Output:

Index

Examples

Constants

View Source
const (
	MesgArgMissing         = "missing argument"
	MesgArgInvalid         = "invalid argument"
	MesgArgInvalidVal      = "invalid value for argument"
	MesgArgInvalidVals     = "invalid combination of values for arguments"
	MesgArgAutoCorrect     = "argument auto-correction"
	MesgAttrAutoCorrect    = "attribute value auto-correction"
	MesgAttrGetProgress    = "returning attribute value..."
	MesgAttrGetSuccess     = "attribute value was returned successfully"
	MesgAttrGetFailure     = "could not get attribute value"
	MesgAttrSetProgress    = "setting attribute value..."
	MesgAttrSetSuccess     = "attribute value was set successfully"
	MesgAttrSetFailure     = "could not set attribute value"
	MesgAttrCheckProgress  = "checking attribute value..."
	MesgAttrCheckSuccess   = "attribute value check successful"
	MesgAttrCheckFailure   = "could not check attribute value"
	MesgAttrValNotDiff     = "attribute value did not change"
	MesgAttrValDiff        = "attribute value changed"
	MesgFileNotDiff        = "file did not change"
	MesgFileDiff           = "file changed"
	MesgInitProgress       = "initializing..."
	MesgInitSuccess        = "initialized successfully"
	MesgInitFailure        = "could not be initialized"
	MesgStartProgress      = "starting..."
	MesgStartSuccess       = "started successfully"
	MesgStartFailure       = "could not be started"
	MesgStopProgress       = "shutting down..."
	MesgStopSuccess        = "shutdown successfully"
	MesgStopFailure        = "could not be shutdown"
	MesgProcProgress       = "processing..."
	MesgProcStarted        = "process started"
	MesgProcSuccess        = "processed successfully"
	MesgProcFailure        = "could not be processed"
	MesgProcFatal          = "could no longer process. exiting."
	MesgProcStopped        = "process stopped"
	MesgConfProgress       = "fetching configuration..."
	MesgConfSuccess        = "configuration loaded successfully"
	MesgConfFailure        = "configuration could not be loaded"
	MesgReqProgress        = "requesting..."
	MesgReqSuccess         = "request completed successfully"
	MesgReqFailure         = "request could not be completed"
	MesgRecCreated         = "record created successfully"
	MesgRecUpdated         = "record updated successfully"
	MesgRecDeleted         = "record deleted successfully"
	MesgRecFound           = "record found successfully"
	MesgRecNotCreated      = "record could not be created"
	MesgRecNotUpdated      = "record could not be updated"
	MesgRecNotDeleted      = "record could not be deleted"
	MesgRecNotFound        = "record could not be found"
	MesgResultUnexpected   = "unexpected result"
	MesgScenarioUnexpected = "did not expect to get here..."
	MesgFuncDeprecated     = "function is deprecated"
	MesgFuncMissUsed       = "function call is not appropriate in this use-case"
	MesgFiberLogger        = "handled request"
	MesgGormTrace          = "trace"
	MesgGormUnknown        = "gorm log format not recognized"
)

List of pre-defined logging messages, helping to standardize log contents.

Variables

This section is empty.

Functions

func Debug

func Debug(msg ...interface{})

func Debugf

func Debugf(template string, args ...interface{})

func Error

func Error(msg ...interface{})

func Errorf

func Errorf(template string, args ...interface{})

func Fatal

func Fatal(msg ...interface{})

func Fatalf

func Fatalf(template string, args ...interface{})

func Info

func Info(msg ...interface{})

func Infof

func Infof(template string, args ...interface{})

func Level

func Level(level ...levels.Type) levels.Type

func Panic

func Panic(msg ...interface{})

func Panicf

func Panicf(template string, args ...interface{})

func Prefix

func Prefix(prefix ...string) string

func Prefixed

func Prefixed(prefix, name string) string

func PrefixedWithSuffix

func PrefixedWithSuffix(prefix, name string) string

func Trace

func Trace(msg ...interface{})

func Tracef

func Tracef(template string, args ...interface{})

func Warn

func Warn(msg ...interface{})

func Warnf

func Warnf(template string, args ...interface{})

Types

type Logger

type Logger interface {
	//                                     NOTE: Methods cannot be declared as part of the exported interface, but are available for all implementations.
	// Named(string) Logger                   // Create a new sub-Logger with a name descending from the current name. This is used to create a subsystem specific Logger.
	// WithLevel(levels.Type) Logger          // Chainable level setter.
	// WithLevelFromDebug(bool) Logger        // Chainable level setter from debug boolean value.
	// Options(...func(Logger) Logger) Logger // Custom chainable setter functions.
	Prefix(...string) string          // Prefix returns current logger name. With a prefix argument, the current logger's name is set to it.
	Level(...levels.Type) levels.Type // Level returns current logging level. With a level argument, the current logger's level is set to it.
	Trace(...interface{})             // Trace logs a message at the Trace level.
	Debug(...interface{})             // Debug logs a message at the Debug level.
	Info(...interface{})              // Info logs a message at the Info level.
	Warn(...interface{})              // Warn logs a message at the Warn level.
	Error(...interface{})             // Error logs a message at the Error level.
	Panic(...interface{})             // Panic logs a message at the Panic level and panics.
	Fatal(...interface{})             // Fatal logs a message at the Fatal level and exists the application.
	Tracef(string, ...interface{})    // Tracef formats a message according to a format specifier and logs the message at the Trace level.
	Debugf(string, ...interface{})    // Debugf formats a message according to a format specifier and logs the message at the Debug level.
	Infof(string, ...interface{})     // Infof formats a message according to a format specifier and logs the message at the Info level.
	Warnf(string, ...interface{})     // Warnf formats a message according to a format specifier and logs the message at the Warning level.
	Errorf(string, ...interface{})    // Errorf formats a message according to a format specifier and logs the message at the Error level.
	Panicf(string, ...interface{})    // Panicf formats a message according to a format specifier and logs the message at the Panic level and then panics.
	Fatalf(string, ...interface{})    // Fatalf formats a message according to a format specifier and logs the message at the Fatal level and exits the application.
}

Logger is an interface for Logging.

var Current Logger

Current contains the logger used for the package level logging functions.

type Map

type Map map[string]interface{}

Map is a shortcut for map[string]interface{} key, values, useful for JSON returns. Where the values can be any Go type, but convertable to a string.

func ParseArgs

func ParseArgs(args ...interface{}) ([]interface{}, Map)

Directories

Path Synopsis
examples
cli
impl
cli
std
NOTE: This package differs from log.Std in the following ways: - Renamed Std struct to Logger.
NOTE: This package differs from log.Std in the following ways: - Renamed Std struct to Logger.
zap
interface
Package io provides a means of turning a log.Logger into an io.Writer for a chosen level.
Package io provides a means of turning a log.Logger into an io.Writer for a chosen level.
middlew

Jump to

Keyboard shortcuts

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