clog

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2018 License: Apache-2.0 Imports: 14 Imported by: 25

README

Clog Build Status GoDoc Sourcegraph

Clog is a channel-based logging package for Go.

This package supports multiple logger adapters across different levels of logging. It uses Go's native channel feature to provide goroutine-safe mechanism on large concurrency.

Installation

To use a tagged revision:

go get gopkg.in/clog.v1

To use with latest changes:

go get github.com/go-clog/clog

Please apply -u flag to update in the future.

Testing

If you want to test on your machine, please apply -t flag:

go get -t gopkg.in/clog.v1

Please apply -u flag to update in the future.

Getting Started

Clog currently has three builtin logger adapters: console, file, slack and discord.

It is extremely easy to create one with all default settings. Generally, you would want to create new logger inside init or main function.

...

import (
	"fmt"
	"os"

	log "gopkg.in/clog.v1"
)

func init() {
	err := log.New(log.CONSOLE, log.ConsoleConfig{})
	if err != nil {
		fmt.Printf("Fail to create new logger: %v\n", err)
		os.Exit(1)
	}

	log.Trace("Hello %s!", "Clog")
	// Output: Hello Clog!

	log.Info("Hello %s!", "Clog")
	log.Warn("Hello %s!", "Clog")
	...
}

...

The above code is equivalent to the follow settings:

...
	err := log.New(log.CONSOLE, log.ConsoleConfig{
		Level:      log.TRACE, // Record all logs
		BufferSize: 0,         // 0 means logging synchronously
	})
...

In production, you may want to make log less verbose and asynchronous:

...
	err := log.New(log.CONSOLE, log.ConsoleConfig{
		// Logs under INFO level (in this case TRACE) will be discarded
		Level:      log.INFO, 
		// Number mainly depends on how many logs will be produced by program, 100 is good enough
		BufferSize: 100,      
	})
...

Console logger comes with color output, but for non-colorable destination, the color output will be disabled automatically.

Error Location

When using log.Error and log.Fatal functions, the first argument allows you to indicate whether to print the code location or not.

...
	// 0 means disable printing code location
	log.Error(0, "So bad... %v", err)

	// To print appropriate code location mainly depends on how deep your call stack is, 
	// you need to try and verify
	log.Error(2, "So bad... %v", err)
	// Output: 2017/02/09 01:06:16 [ERROR] [...uban-builder/main.go:64 main()] ...
	log.Fatal(2, "Boom! %v", err)
	// Output: 2017/02/09 01:06:16 [FATAL] [...uban-builder/main.go:64 main()] ...
...

Calling log.Fatal will exit the program.

File

File logger is more complex than console, and it has ability to rotate:

...
	err := log.New(log.FILE, log.FileConfig{
		Level:              log.INFO, 
		BufferSize:         100,  
		Filename:           "clog.log",  
		FileRotationConfig: log.FileRotationConfig {
			Rotate: true,
			Daily:  true,
		},
	})
...

Slack

Slack logger is also supported in a simple way:

...
	err := log.New(log.SLACK, log.SlackConfig{
		Level:              log.INFO, 
		BufferSize:         100,  
		URL:                "https://url-to-slack-webhook",  
	})
...

This logger also works for Discord Slack endpoint.

Discord

Discord logger is supported in rich format via Embed Object:

...
	err := log.New(log.DISCORD, log.DiscordConfig{
		Level:              log.INFO, 
		BufferSize:         100,  
		URL:                "https://url-to-discord-webhook",  
	})
...

This logger also retries automatically if hits rate limit after retry_after.

Credits

License

This project is under Apache v2 License. See the LICENSE file for the full license text.

Documentation

Overview

Clog is a channel-based logging package for Go.

Index

Constants

View Source
const (
	SIMPLE_DATE_FORMAT = "2006-01-02"
	LOG_PREFIX_LENGTH  = len("2017/02/06 21:20:08 ")
)

Variables

This section is empty.

Functions

func Delete

func Delete(mode MODE)

Delete removes logger from the receiver list.

func Error

func Error(skip int, format string, v ...interface{})

func Fatal

func Fatal(skip int, format string, v ...interface{})

func Info

func Info(format string, v ...interface{})

func New

func New(mode MODE, cfg interface{}) error

New initializes and appends a new logger to the receiver list. Calling this function multiple times will overwrite previous logger with same mode.

func NewFileWriter added in v1.1.0

func NewFileWriter(filename string, cfg FileRotationConfig) (io.Writer, error)

NewFileWriter returns an io.Writer for synchronized file logger in standalone mode.

func Register

func Register(mode MODE, f Factory)

func Shutdown

func Shutdown()

func Trace

func Trace(format string, v ...interface{})

func Version

func Version() string

Version returns current version of the package.

func Warn

func Warn(format string, v ...interface{})

func Write

func Write(level LEVEL, skip int, format string, v ...interface{})

Types

type Adapter

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

Adapter contains common fields for any logger adapter. This struct should be used as embedded struct.

type ConsoleConfig

type ConsoleConfig struct {
	// Minimum level of messages to be processed.
	Level LEVEL
	// Buffer size defines how many messages can be queued before hangs.
	BufferSize int64
}

type DiscordConfig added in v1.2.0

type DiscordConfig struct {
	// Minimum level of messages to be processed.
	Level LEVEL
	// Buffer size defines how many messages can be queued before hangs.
	BufferSize int64
	// Discord webhook URL.
	URL string
	// Username to be shown for the message.
	// Leave empty to use default as set in the Discord.
	Username string
}

type ErrConfigObject

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

func (ErrConfigObject) Error

func (err ErrConfigObject) Error() string

type ErrInvalidLevel

type ErrInvalidLevel struct{}

func (ErrInvalidLevel) Error

func (err ErrInvalidLevel) Error() string

type Factory

type Factory func() Logger

type FileConfig

type FileConfig struct {
	// Minimum level of messages to be processed.
	Level LEVEL
	// Buffer size defines how many messages can be queued before hangs.
	BufferSize int64
	// File name to outout messages.
	Filename string
	// Rotation related configurations.
	FileRotationConfig
}

type FileRotationConfig

type FileRotationConfig struct {
	// Do rotation for output files.
	Rotate bool
	// Rotate on daily basis.
	Daily bool
	// Maximum size in bytes of file for a rotation.
	MaxSize int64
	// Maximum number of lines for a rotation.
	MaxLines int64
	// Maximum lifetime of a output file in days.
	MaxDays int64
}

FileRotationConfig represents rotation related configurations for file mode logger. All the settings can take effect at the same time, remain zero values to disable them.

type LEVEL

type LEVEL int
const (
	TRACE LEVEL = iota
	INFO
	WARN
	ERROR
	FATAL
)

type Logger

type Logger interface {
	// Level returns minimum level of given logger.
	Level() LEVEL
	// Init accepts a config struct specific for given logger and performs any necessary initialization.
	Init(interface{}) error
	// ExchangeChans accepts error channel, and returns message receive channel.
	ExchangeChans(chan<- error) chan *Message
	// Start starts message processing.
	Start()
	// Destroy releases all resources.
	Destroy()
}

Logger is an interface for a logger adapter with specific mode and level.

type MODE

type MODE string
const (
	CONSOLE MODE = "console"
	FILE    MODE = "file"
	SLACK   MODE = "slack"
	DISCORD MODE = "discord"
)

type Message

type Message struct {
	Level LEVEL
	Body  string
}

Message represents a log message to be processed.

type SlackConfig

type SlackConfig struct {
	// Minimum level of messages to be processed.
	Level LEVEL
	// Buffer size defines how many messages can be queued before hangs.
	BufferSize int64
	// Slack webhook URL.
	URL string
}

Jump to

Keyboard shortcuts

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