glogger

package module
v0.0.0-...-67463e6 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2015 License: Apache-2.0 Imports: 12 Imported by: 2

README

glogger

GoDoc

Travis CI

A python-like logging library for go

Getting Started

Install glogger package:

go get github.com/Xuyuanp/glogger

Create your go file. We'll call it hello.go.

package main

import (
    "github.com/Xuyuanp/glogger"
    )

func main() {
    glogger.Default().Debug("Hello world!")
    glogger.Default().Info("Hello world again!")
)

Then run your code:

go run hello.go

You will now see the logging output in the terminal.

Configuration Instruction

Config file is written in json format.

  • filters: filter list. (nothing currently)
  • formatters: formatter list.
    1. builder: formatter builder name.
      • github.com/Xuyuanp/glogger.DefaultFormatter: default formatter builder.
      • github.com/Xuyuanp/glogger/formatters.RainbowFormatter: format record colorized.
    2. fmt: the log message format. The following macros can be used with ${} (optional):
      • name: logger name
      • levelno: log level number
      • levelname: log level name
      • time: current time
      • lfile: file name with absolute path
      • sfile: file name
      • line: current code line
      • func: function name
      • msg: log message
      • other color macro for RainbowFormatter
    3. timefmt: format of time. (optional)
    4. colors: color map for RainbowFormatter. See the config sample above. (optional)
  • handlers: handler list.
    1. builder: handler builder name, values:
      • github.com/Xuyuanp/glogger.StreamHandler: Output log message into stream. (default)
      • github.com/Xuyuanp/glogger/handlers.FileHandler: Output log message into file.
      • github.com/Xuyuanp/glogger/handlers.RotatingFileHandler: Output log message into file and auto-rotate.
      • github.com/Xuyuanp/glogger/handlers.SMTPHandler: Output log message via SMTP.
    2. level: log level, values: (optional)
      • DEBUG (default)
      • INFO
      • WARNING
      • ERROR
      • CRITICAL
    3. filters: filter name list. (optional)
    4. formatter: formatter name, DefaultFormatter if not supplied. (optional)
    5. writer: the output stream, for StreamHandler. (optional)
      • stdout: standard output (default)
      • stderr: standard error
    6. filename: file name, for FileHandler and RotatingFileHandler. (required)
    7. autoRotate: if enable log file auto-rotate. Boolean value, true or false. For RotatingFileHandler. (optional, true as default)
    8. maxSize: max size (byte) of log file. Integer value, 0 means unlimited. For RotatingFileHandler. (optional, 0 as default)
    9. maxLine: max line of log file. Integer value, 0 means unlimited. For RotatingFileHandler. (optional, 0 as default)
    10. daily: if auto-rotate log file daily. Boolean value, true or false. For RotatingFileHandler. (optional, true as default)
    11. address: email address to send log message from, for SMTPHandler. (required)
    12. username: SMTP server username, for SMTPHandler. (required)
    13. password: SMTP server password, for SMTPHandler. (required)
    14. to: target email address list, for SMTPHandler. (required)
    15. subject: email subject, for SMTPHandler. (required)
  • loggers: logger list.
    1. level: log level. default is DEBUG. (optional)
    2. filters: filter name list. (optional)
    3. handlers: handler name list, default is StreamHandler. (optional)

Further Sample

Code
package main

import (
    "github.com/Xuyuanp/glogger"
    _ "github.com/Xuyuanp/glogger/formatters"
    _ "github.com/Xuyuanp/glogger/handlers"
)

func init() {
    glogger.LoadConfigFromFile("log.conf")
}

func main() {
    logger := glogger.GetLogger("main")

    logger.Debug("This DEBUG message")
    logger.Info("This is INFO message")
    logger.Warning("This is WARNING message")
    logger.Error("This is ERROR message")
    logger.Critical("This is CRITICAL message")
}
Config file: log.conf
{
    "formatters": {
        "default": {
            "builder": "github.com/Xuyuanp/glogger.DefaultFormatter",
            "fmt": "${time} ${levelname} ${sfile}:${line} ${msg}",
            "timefmt": "2006-01-02 15:04:05"
        },
        "rainbow": {
            "builder": "github.com/Xuyuanp/glogger/formatters.RainbowFormatter",
            "fmt": "${log_color}[${time} ${levelname} ${sfile}:${line} ${func}] ${msg}",
            "timefmt": "01-02-2006 15:04:05",
            "colors": {
                "DEBUG":    "blue",
                "INFO":     "green",
                "WARNING":  "yellow",
                "ERROR":    "cyan",
                "CRITICAL": "red"
            }
        }
    },
    "handlers": {
        "file": {
            "builder": "github.com/Xuyuanp/glogger/handlers.FileHandler",
            "level": "INFO",
            "formatter": "default",
            "filename": "log/record.log"
        },
        "console": {
            "builder": "github.com/Xuyuanp/glogger.StreamHandler",
            "level": "DEBUG",
            "writer": "stdout",
            "formatter": "rainbow"
        }
    },
    "loggers": {
        "main": {
            "level": "DEBUG",
            "handlers": ["console", "file"]
        }
    }
}

Result

Imgur

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AutoRoot = true

AutoRoot is a switcher that controlls GetLogger result

View Source
var DefaultFormat = "[${time} ${levelname} ${sfile}:${line}] ${msg}"

DefaultFormat is default format of log message

View Source
var DefaultTimeFormat = "2006-01-02 15:04:05"

DefaultTimeFormat is default time format

View Source
var FieldHolderRegexp = regexp.MustCompile(`\$\{\w+\}`)

FieldHolderRegexp

View Source
var LevelToString = map[LogLevel]string{
	DebugLevel:    "DBUG",
	InfoLevel:     "INFO",
	WarnLevel:     "WARN",
	ErrorLevel:    "ERRO",
	CriticalLevel: "CRIT",
}

LevelToString is a map to translate LogLevel to a level name string

View Source
var StringToLevel = map[string]LogLevel{
	"DEBUG":    DebugLevel,
	"INFO":     InfoLevel,
	"WARNING":  WarnLevel,
	"ERROR":    ErrorLevel,
	"CRITICAL": CriticalLevel,
}

StringToLevel is a map to translate level name to LogLevel type

Functions

func LoadConfig

func LoadConfig(config []byte) error

LoadConfig parse the json format configuration.

func LoadConfigFromFile

func LoadConfigFromFile(fileName string) error

LoadConfigFromFile read file's content and call the LoadConfig method.

func RegisterConfigLoaderBuilder

func RegisterConfigLoaderBuilder(name string, builder ConfigLoaderBuilder)

RegisterConfigLoaderBuilder register the builder whith name.

func RegisterFilter

func RegisterFilter(name string, filter Filter)

RegisterFilter register a Filter with the name

func RegisterFormatter

func RegisterFormatter(name string, formatter Formatter)

RegisterFormatter register a formatter with the name

func RegisterHandler

func RegisterHandler(name string, handler Handler)

RegisterHandler register a Handler to global manager with specific name. The Handler registered can be accessed by GetHandler method anywhere with this name.

func RegisterLogger

func RegisterLogger(name string, l *Logger)

RegisterLogger will register the logger to global manager. The logger registered can be accessed by GetLogger() method with logger's name.

Types

type ConfigLoader

type ConfigLoader interface {
	LoadConfig(m map[string]interface{}) error
}

ConfigLoader provide method to load config from bytes, string or a file.

type ConfigLoaderBuilder

type ConfigLoaderBuilder func() ConfigLoader

ConfigLoaderBuilder is a function which return a ConfigLoader.

func GetConfigLoaderBuilder

func GetConfigLoaderBuilder(name string) ConfigLoaderBuilder

GetConfigLoaderBuilder return a ConfigLoaderBuilder registered with this name

type DefaultFormatter

type DefaultFormatter struct {
	TimeFmt string `json:timefmt`
	Fmt     string `json:fmt`
}

DefaultFormatter struct

func NewDefaultFormatter

func NewDefaultFormatter() *DefaultFormatter

NewDefaultFormatter return a new DefaultFormatter

func (*DefaultFormatter) Format

func (df *DefaultFormatter) Format(rec *Record) string

Format formats a record to string

func (*DefaultFormatter) LoadConfig

func (df *DefaultFormatter) LoadConfig(config map[string]interface{}) error

LoadConfig load configuration from a map

func (*DefaultFormatter) LoadConfigJSON

func (df *DefaultFormatter) LoadConfigJSON(config []byte) error

LoadConfigJSON load configuration from json

type Filter

type Filter interface {
	ConfigLoader
	Filter(rec *Record) bool
}

Filter interface

func GetFilter

func GetFilter(name string) Filter

GetFilter return a Filter regeistered by the name

type Formatter

type Formatter interface {
	ConfigLoader
	Format(rec *Record) string
}

Formatter interface

func GetFormatter

func GetFormatter(name string) Formatter

GetFormatter return formater regeistered by the name

type GenericHandler

type GenericHandler struct {
	GroupFilter
	// contains filtered or unexported fields
}

GenericHandler is an abstract struct which fully implemented Handler interface expected Emit method.

func NewHandler

func NewHandler() *GenericHandler

NewHandler return a new GenericHandler

func (*GenericHandler) Format

func (gh *GenericHandler) Format(rec *Record) string

Format a record with formatter

func (*GenericHandler) Level

func (gh *GenericHandler) Level() LogLevel

Level return log level of the handler

func (*GenericHandler) LoadConfig

func (gh *GenericHandler) LoadConfig(config map[string]interface{}) error

LoadConfig load configuration from a map

func (*GenericHandler) SetFormatter

func (gh *GenericHandler) SetFormatter(formatter Formatter)

SetFormatter set a new Formatter

func (*GenericHandler) SetLevel

func (gh *GenericHandler) SetLevel(level LogLevel)

SetLevel set log level of handler

type GroupFilter

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

GroupFilter struct

func (*GroupFilter) AddFilter

func (f *GroupFilter) AddFilter(ft Filter)

AddFilter add a filter to a filter list

func (*GroupFilter) Filter

func (f *GroupFilter) Filter(rec *Record) bool

Filter return true only if all the filters return true, or false if not

func (*GroupFilter) LoadConfig

func (f *GroupFilter) LoadConfig(config map[string]interface{}) error

LoadConfig load configuration from a map, not implemented currenttly

type Handler

type Handler interface {
	Leveler
	Filter
	Handle(rec *Record)
}

Handler determines where the log message to output

func GetHandler

func GetHandler(name string) Handler

GetHandler return the Handler registered with this name. nil will by returned if no Handler registered with this name.

type Leveler

type Leveler interface {
	Level() LogLevel
	SetLevel(level LogLevel)
}

Leveler is an interface provided set/get LogLevel method

type LogLevel

type LogLevel uint8

LogLevel type

const (
	DebugLevel LogLevel = iota
	InfoLevel
	WarnLevel
	ErrorLevel
	CriticalLevel
)

LogLevel values

func (LogLevel) String

func (level LogLevel) String() string

type Logger

type Logger struct {
	GroupFilter

	Name  string
	Level LogLevel
	// contains filtered or unexported fields
}

Logger is the default Logger

func Default

func Default() *Logger

Default functions return a logger registered by name 'root', or a new Logger with default Handler and Formatter, and registered as 'root' automatically.

func GetLogger

func GetLogger(name string) *Logger

GetLogger return a Logger registered with the name, or the root Logger if AutoRoot is true and name is not root, or nil

func NewLogger

func NewLogger() *Logger

NewLogger return a new Logger with debug level as default.

func UnregisterLogger

func UnregisterLogger(name string) *Logger

UnregisterLogger unregister the logger from global manager, this will make the logger unreachable for others and return the logger, this's the last chance getting it. If this Logger hasn't been registered, nothing will happen and return nil

func (*Logger) AddHandler

func (hg *Logger) AddHandler(h Handler)

func (*Logger) ClearHandlers

func (hg *Logger) ClearHandlers()

func (*Logger) Critical

func (l *Logger) Critical(f string, v ...interface{})

Critical see details in Logger interface

func (*Logger) Debug

func (l *Logger) Debug(f string, v ...interface{})

Debug see details in Logger interface

func (*Logger) Error

func (l *Logger) Error(f string, v ...interface{})

Error see details in Logger interface

func (*Logger) Handle

func (hg *Logger) Handle(rec *Record)

func (*Logger) Info

func (l *Logger) Info(f string, v ...interface{})

Info see details in Logger interface

func (*Logger) LoadConfig

func (l *Logger) LoadConfig(config map[string]interface{}) error

LoadConfig loads configuration from map.

func (*Logger) SetHandlers

func (hg *Logger) SetHandlers(handlers ...Handler)

func (*Logger) Warning

func (l *Logger) Warning(f string, v ...interface{})

Warning see details in Logger interface

type Record

type Record struct {
	Name    string    // logger name
	Level   LogLevel  // log level
	Time    time.Time // log time
	LFile   string    // full file name
	SFile   string    // final file name
	Line    int       // line number
	Func    string    // function name
	Message string    // log message
}

Record is a struct contains all the logging information

func NewRecord

func NewRecord(name string, t time.Time, level LogLevel, file string, funcname string, line int, msg string) *Record

NewRecord return a new Record

type Register

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

Register is a thread-safe map

func NewRegister

func NewRegister() *Register

NewRegister returns a new register.

func (*Register) Get

func (r *Register) Get(name string) interface{}

Get return an interface registerd with this name.

func (*Register) Register

func (r *Register) Register(name string, v interface{})

Register binds the interface and the name. If this name has been registerd, it panics.

func (*Register) Unregister

func (r *Register) Unregister(name string) interface{}

Unregister unbinds the interface and the name. It returns the interface or nil

type StreamHandler

type StreamHandler struct {
	*GenericHandler
	// contains filtered or unexported fields
}

StreamHandler struct

func NewStreamHandler

func NewStreamHandler() *StreamHandler

NewStreamHandler return a new StreamHandler

func (*StreamHandler) Handle

func (sh *StreamHandler) Handle(rec *Record)

Handle a Record

func (*StreamHandler) LoadConfig

func (sh *StreamHandler) LoadConfig(config map[string]interface{}) error

LoadConfig load configuration from a map

func (*StreamHandler) SetWriter

func (sh *StreamHandler) SetWriter(writer io.Writer)

SetWriter set a output writer

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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