elog

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2019 License: MIT Imports: 7 Imported by: 26

README

elog

GoDoc Build Status

elog extends Go's built-in log package to enable simple levelled logging and to modify the formatting.

Debugging mode

The debugging mode can be enabled by setting the configured environment variable ("DEBUG" by default) to 1. Alternatively, the debugging can be enabled using a flag.

Usage

Get the package

go get github.com/farshidtz/elog

Import

import "github.com/farshidtz/elog"

Examples

10	// Initialize with the default configuration
11	logger := elog.New("[main] ", nil)
12	
13	logger.Println("Hello world!")
14	logger.Debugln("Hello world!")
15	logger.Fatalln("Hello world!")

Debugging not enabled

2016/07/14 16:47:04 [main] Hello world!
2016/07/14 16:47:04 [main] Hello world!
exit with status 1

Debugging enabled

2016/07/14 16:47:04 [main] main.go:13: Hello world!
2016/07/14 16:47:04 [debug] main.go:14 Hello world!
2016/07/14 16:47:04 [main] main.go:15 Hello world!
exit with status 1
Error logging
01	package main
02
03	import "github.com/farshidtz/elog"
04
05	var logger *elog.Logger
06
07	func main() {
08		logger = elog.New("[main] ", nil)
09
10		v, err := divide(10, 0)
11		if err != nil {
12			logger.Fatalln(err)
13		}
14		logger.Println(v)
15	}
16
17	func divide(a, b int) (float64, error) {
18		if b == 0 {
19			return 0, logger.Errorf("Cannot divide by zero")
20			// The error is logged in debugging mode
21		}
22		return float64(a) / float64(b), nil
23	}

Debugging not enabled

2016/07/20 16:38:31 [main] main.go:12: Cannot divide by zero

Debugging enabled

2016/07/20 16:38:31 [debug] main.go:19: Cannot divide by zero
2016/07/20 16:38:31 [main] main.go:12: Cannot divide by zero
Configuration
10	logger := elog.New("[I] ", &elog.Config{
11	  TimeFormat: time.RFC3339, 
12	  DebugPrefix: "[D] ", 
13	})
14	
15	logger.Println("Hello world!")
16	logger.Debugln("Hello world!")
17	logger.Fatalln("Hello world!")

Debugging not enabled

2016-07-14T16:57:15Z [I] Hello world!
2016-07-14T16:57:15Z [I] Hello world!
exit with status 1

Debugging enabled

2016-07-14T16:57:15Z [I] main.go:15 Hello world!
2016-07-14T16:57:15Z [D] main.go:16 Hello world!
2016-07-14T16:57:15Z [I] main.go:17 Hello world!
exit with status 1
Initialization with init()

Alternatively, a global logger can be instantiated in the init() function and used throughout the package.

import "github.com/farshidtz/elog"

var logger *elog.Logger

func init() {
	logger = elog.New("[main] ", nil)
}
Enable debugging with a flag
package main

import (
	"github.com/farshidtz/elog"
	"flag"
)

var debugFlag = flag.Bool("d", false, "Enable debugging")
func main() {
	flag.Parse()
	logger := elog.New("[main] ", &elog.Config{
	  DebugEnabled: debugFlag,
	})
	
	logger.Println("Hello World!")
	logger.Debugln("Hello World!")
}

Example (Windows PowerShell):

PS C:\logging> .\main.exe
2016/07/20 15:55:31 [main] Hello World!

PS C:\logging> .\main.exe -d
2016/07/20 15:55:32 [main] main.go:15: Hello World!
2016/07/20 15:55:32 [debug] main.go:16: Hello World!
Setting an environment variable
Unix:
export DEBUG=1

Command Prompt:
set DEBUG=1

PowerShell:
$env:DEBUG=1

Documentation

For Go log's build-in methods: golang.org/pkg/log

For extended elog methods: godoc.org/github.com/farshidtz/elog

Documentation

Overview

Package elog extends Go's built-in log package to enable levelled logging with improved formatting.

Methods

Inherited from the log package (https://golang.org/pkg/log):

func (l *Logger) Print(v ...interface{})
func (l *Logger) Printf(format string, v ...interface{})
func (l *Logger) Println(v ...interface{})
func (l *Logger) Output(calldepth int, s string) error

func (l *Logger) Fatal(v ...interface{})
func (l *Logger) Fatalf(format string, v ...interface{})
func (l *Logger) Fatalln(v ...interface{})

func (l *Logger) Panic(v ...interface{})
func (l *Logger) Panicf(format string, v ...interface{})
func (l *Logger) Panicln(v ...interface{})

Extensions:

func (l *Logger) Debug(a ...interface{})
func (l *Logger) Debugf(format string, a ...interface{})
func (l *Logger) Debugln(a ...interface{})
func (l *Logger) DebugOutput(calldepth int, s string)

func (l *Logger) Errorf(format string, a ...interface{}) error

Index

Constants

View Source
const (
	NoTrace   = 1              // no file name or line lumber
	LongFile  = log.Llongfile  // absolute file path and line number: /home/user/go/main.go:15
	ShortFile = log.Lshortfile // file name and line number: main.go:15
)

Variables

This section is empty.

Functions

func NewWriter

func NewWriter(w io.Writer, timeFormat ...string) *writer

NewWriter returns a new io.Writer that writes timestamps as prefix

E.g. usage:

logger := log.New(elog.NewWriter(os.Stdout), "[info] ", 0)
logger.Println("Hello.")

Prints: 2016/07/19 17:34:10 [info] Hello.

Types

type Config

type Config struct {
	// Writer is the destination to which log data is written
	// Default: os.Stdout
	Writer io.Writer
	// TimeFormat is the format of time in the prefix (compatible with https://golang.org/pkg/time/#pkg-constants)
	// Default: "2006/01/02 15:04:05"
	TimeFormat string
	// Trace is to control the tracing information
	// Default: NoTrace
	Trace int
	// DebugEnabled can be used to pass a parsed command-line boolean flag to enable the debugging
	// Default: nil
	DebugEnabled *bool
	// DebugEnvVar is the environment variable used to enable debugging when set to 1
	// Default: "DEBUG"
	DebugEnvVar string
	// DebugPrefix is the prefix used when logging with Debug methods and Errorf
	// Default: "[debug] "
	DebugPrefix string
	// DebugTrace is to control the tracing information when in debugging mode
	// Default: ShortFile
	DebugTrace int
}

type Logger

type Logger struct {
	*log.Logger
	// contains filtered or unexported fields
}

func New

func New(prefix string, config *Config) *Logger

New creates a new Logger. The prefix variable is the prefix used when logging with Print, Fatal, and Panic methods. The config variable is a struct with optional fields.

When config is set to nil, the default configuration will be used.

func (*Logger) Debug

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

Debug has similar arguments to those of fmt.Print. It prints to the logger only when debugging is enabled.

func (*Logger) DebugOutput

func (l *Logger) DebugOutput(calldepth int, s string)

DebugOutput is similar to Debug but allows control over the scope of tracing. (log.Output for debugging)

E.g. :

[main.go]

10  apiError("error message")
11
12  // A function to log formatted API errors
13  func apiError(s string){
14     logger.DebugOutput(2, "API Error:", s)
15  }

Prints: 2016/07/19 17:34:10 [debug] main.go:10: API Error: error message

func (*Logger) Debugf

func (l *Logger) Debugf(format string, a ...interface{})

Debugf has similar arguments to those of fmt.Printf. It prints to the logger only when debugging is enabled.

func (*Logger) Debugln

func (l *Logger) Debugln(a ...interface{})

Debugln has similar arguments to those of fmt.Println. It prints to the logger only when debugging is enabled.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, a ...interface{}) error

Errorf has similar arguments and signature to those of fmt.Errorf. In addition to formatting and returning error, Errorf prints the error message to the logger when debugging is enabled.

E.g. :

[example.go]

19  func DoSomething() error {
20    err, v := divide(10, 0)
21    if err != nil {
22      return logger.Errorf("Division error: %s", err)
23    }
24
25    return nil
24  }

Prints: 2016/07/19 17:44:22 [debug] example.go:22: Division error: cannot divide by zero

Jump to

Keyboard shortcuts

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