rlog

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2014 License: MIT Imports: 10 Imported by: 0

README

rlog introduction

rlog is an advanced logging library for GO supporting various output modules, log levels, filtering and tagging. The API is very similar to the API of the GO log standard library but differs because the API of the standard logging library cannot carry enough information to support advanced features found to be useful in larger production environments.

How to contribute

Bug fixes, code improvements and additional output modules are always welcome.

Usage

rlog is comprised of a core and various output modules (each implemented in its own package).

Example: stdout and syslog

First, use EnableModule() to activate the syslog logger and the stdout logger (log output is written to both sources). Next, initialize the rlog core by calling Start() and passing a configuration. The deferred flush call ensures that output is written before the application terminates.

func main(){
	syslogModule, err := syslog.NewLocalSyslogLogger()
	if err != nil {
		panic("Getting syslog logger instance failed")
	}

	rlog.EnableModule(syslogModule)
	rlog.EnableModule(stdout.NewStdoutLogger(true))
	rlog.Start(rlog.GetDefaultConfig())
	defer rlog.Flush()

	//Write your code here
}

Architecture & details

This section describes how rlog works internally and interacts with the various output modules. This is useful for people who want to understand the internals of rlog or would like to contribute to it.

Core

The core implements the user facing API, message formatting, stack trace retrieval (depending on the severity of the log message) and submission to the various registered output modules. The basic processing steps:

1. User submits log message through rlog API
2. Drop message if tag or log level criteria match
3. Retrieve and cut stack trace if log message is error or fatal
4. Forward message to each module

Output modules

To be compatible with the rlog core, all output modules must implement the "rlogModule" interface providing a message channel and a flush command channel. Log messages are sent through the message channel using the message format defined in common/RlogMsg.

Each output module is launched by the rlog core upon a call rlog.Start(...) and runs in its own goroutine. This isolates the output module from the rlog core. So even if an IO operation takes a long time, the caller of rlog will not be effected by this.

Furthermore, all channel operations performed by the rlog core are non-blocking. This ensures that even if an output module crashes (e.g. not accepting log messages anymore), the rlog caller (your application) is not blocked rlog.

Writing an output module

To write an rlog module, the following steps are required:

1. Create a new package and give it an expressive, short name
2. Write a "LaunchModule" function to satisfy the "rlogModule" interface
3. Import package "common" to obtain access to the log message type
4. Write a constructor returning an instance of the log module. Use arguments to obtain configuration.

Running the unit tests

Tests for rlog are written using the "gocheck" testing framework (providing fixtures, etc.). Before running "go test", please fetch the following additional library:

go get launchpad.net/gocheck

License

The MIT License (MIT)

Copyright (c) 2013 brsc

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package rlog is an advanced and extensible logger for Go.

Package rlog implements the core logging facility, which are the user API and log message processing. The rlog output modules are producing the output, i.e. without any enabled modules, rlog does not produce any output. Note that all methods provided by rlog are thread safe.

Configuring rlog & enabling modules

Output modules offer a "new" method to create a new instance for that particular output type and rlog offers the EnableModule method to enable each method satisfying the required interface provided by the rlog. rlog is configured by retrieving and modifying the default configuration using the GetDefaultConfig() method. Once started, rlog's configuration cannot be modified. rlog is usually initialized in main. When calling "rlog.Start()", it is advisable to call "defer rlog.Flush() right after to ensure that upon termination of the main method, all log entries are written.

Example setup procedure with stdout and syslog output:

syslogModule, err := syslog.NewLocalSyslogLogger()
if err != nil {
	panic("Getting syslog logger instance failed")
}

rlog.EnableModule(syslogModule)
rlog.EnableModule(stdout.NewStdoutLogger(true))
rlog.Start(rlog.GetDefaultConfig())
defer rlog.Flush()

Example: setup using tags

const TAG1 string = "tag1"
const TAG2 string = "tags"

//Start rlog, display only msg carrying TAG1
rlog.EnableModule(stdout.NewStdoutLogger(true))
conf := rlog.GetDefaultConfig()
conf.DisableTagsExcept([]string{TAG1})
rlog.Start(conf)
defer rlog.Flush()

//Output tagged messages
rlog.InfoT(TAG1, "This msg appears")
rlog.InfoT(TAG2, "This msg does NOT appear")

Producing log output

rlog exists as a singleton and output can be produced by simply importing the rlog package and calling the various print messages on it. Output methods ending with a T (e.g. infoT) require a tag argument. Tags are user defined strings. It is highly recommended to define tags as constants to avoid typos. Tags are currently NOT implemented.

Example:

rlog.Debug("debug log entry")
rlog.Info("info log entry")
rlog.ErrorT(DATABASE, "Connection terminated")
rlog.Fatal("fatal log entry")

Generating IDs

GenerateID() generates a unique, hex formatted string ID. The initial value is random and each successive call increments it.

Log objects

Log objects are can be retrieved using the NewLogger method. The user gets back an object referring to the singleton logger, offering the same API as the rlog package. This allows to mock rlog package using an interface requirement when generating shared libraries.

Index

Constants

View Source
const (
	SeverityFatal   common.RlogSeverity = iota
	SeverityError   common.RlogSeverity = iota
	SeverityWarning common.RlogSeverity = iota
	SeverityInfo    common.RlogSeverity = iota
	SeverityDebug   common.RlogSeverity = iota
)

===== severity levels map to a couple of constants =====

Variables

This section is empty.

Functions

func Debug

func Debug(format string, a ...interface{})

Debug logs a message of severity "debug". Arguments: printf formatted message

func DebugT

func DebugT(tag string, format string, a ...interface{})

DebugT logs a message of severity "debug". Arguments: tag and printf formatted message

func EnableModule

func EnableModule(module rlogModule)

EnableModule activates an output module Arguments: module to be activated, must implement the rlogModule interface

func Error

func Error(format string, a ...interface{})

Error logs a message of severity "error". Arguments: printf formatted message

func ErrorT

func ErrorT(tag string, format string, a ...interface{})

ErrorT logs a message of severity "error". Arguments: tag and printf formatted message

func Fatal

func Fatal(format string, a ...interface{})

Fatal logs a message of severity "fatal". Arguments: printf formatted message

func FatalT

func FatalT(tag string, format string, a ...interface{})

FatalT logs a message of severity "fatal". Arguments: tag and printf formatted message

func Flush

func Flush()

Flush should be called before the program using RightLog4Go exits (e.g. by using defer in main). Flush notifies the registered logger modules to write back their buffered data.

func GenerateID

func GenerateID() string

GenerateID creates a unique ID, i.e. two calls to GenerateID are guaranteed to return different IDs Returns: unique ID

func Info

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

Info logs a message of severity "info". Arguments: printf formatted message

func InfoT

func InfoT(tag string, format string, a ...interface{})

InfoT logs a message of severity "info". Arguments: tag and printf formatted message

func NewLogger

func NewLogger() *logger

Newlogger creates a new instance of the logger struct. The entire interface for writing log messages is available on top of a logger and calls the singleton rlog instance. In contrast to using the rlog package directly, a logger can satisfy a log interface required by an external library and so decouple the rlog package from the library logger.

func ResetState added in v0.4.0

func ResetState()

Performs a reset of rlog state, intended for testing purposes only (with or without flushing before-hand). Applications should call Flush() but should usually not reset state. A reset is needed for unit testing due to rlog being a singleton. Tests that leverage rlog therefore cannot be run in parallel and also call reset state.

func Start

func Start(conf RlogConfig)

Start configures the logger and launches it. Once the logger is started, it cannot be started again. Start is not thread safe: use Start before spawning any goroutine using the logger. Arguments: logger configuration.

func Warning added in v0.4.0

func Warning(format string, a ...interface{})

Warning logs a message of severity "warning". Arguments: printf formatted message

func WarningT added in v0.4.0

func WarningT(tag string, format string, a ...interface{})

WarningT logs a message of severity "warning". Arguments: tag and printf formatted message

Types

type RlogConfig

type RlogConfig struct {
	ChanCapacity uint32 //Buffer capacity for communication between logger and each module
	FlushTimeout uint32 //Max time for rlog modules to write-back their data (seconds)
	Severity     common.RlogSeverity
	// contains filtered or unexported fields
}

RlogConfig holds the logger configuration. It allows rlog users to configure the logger.

func GetDefaultConfig

func GetDefaultConfig() RlogConfig

GetDefaultConfig returns a default configuration for the core logger. Only logging to syslog is activated (to be implemented). Returns: struct holding default configuration

func (*RlogConfig) DisableTagsExcept

func (c *RlogConfig) DisableTagsExcept(tags []string)

DisableTagsExcept enables output for messages carrying one of the tags specified. All other log messages are filtered. Using "DisableTagsExcept" overwrites the settings from "EnableTagsExcept".

func (*RlogConfig) EnableTagsExcept

func (c *RlogConfig) EnableTagsExcept(tags []string)

EnableTagsExcept enables output for all messages except the ones carrying one of the tags specified. Using "EnableTagsExcept" overwrites the settings from "DisableTagsExcept".

func (*RlogConfig) SeverityFromString added in v0.4.0

func (c *RlogConfig) SeverityFromString(value string)

===== Configuration API ===== converts the given string value to log level (severity).

value: to convert

Directories

Path Synopsis
Package common contains data structures and constants shared between rlog and its modules.
Package common contains data structures and constants shared between rlog and its modules.
Implements a console logger for stdout/stderr.
Implements a console logger for stdout/stderr.
Package file implements an output module for logging to a file using rlog.
Package file implements an output module for logging to a file using rlog.
Deprecated.
Deprecated.
Package syslog implements an output module for logging to syslog using rlog.
Package syslog implements an output module for logging to syslog using rlog.
Package test contains integration testing packages for rlog.
Package test contains integration testing packages for rlog.
loggerObject
Application loggerObjects are test permutations testing rlog logObjects.
Application loggerObjects are test permutations testing rlog logObjects.
modules
Application modules are test permutations testing various rlog output modules.
Application modules are test permutations testing various rlog output modules.
tags
Application tags are test permutations testing tag based filtering in rlog.
Application tags are test permutations testing tag based filtering in rlog.
with_gocheck
Implements an on-failure-only gocheck package logger.
Implements an on-failure-only gocheck package logger.
with_testing
Implements an on-failure-only testing package logger.
Implements an on-failure-only testing package logger.

Jump to

Keyboard shortcuts

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