xlog

package module
v0.0.0-...-8752a01 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2019 License: MIT Imports: 11 Imported by: 7

README

xlog

plugin architecture and flexible log system for golang

Build Status Go Report Card GoDoc

Installation

go get github.com/xfxdev/xlog

Usage

import (
    "github.com/xfxdev/xlog"
)

strLogLevel := "INFO"  // also maybe read from config.
logLevel, suc := xlog.ParseLevel(strLogLevel)
if suc == false {
    // failed to parse log level, will use the default level[INFO] instead."
}
xlog.SetLevel(logLevel)

// write log to file.
w2f, err := xlog.NewW2FileListener("")
if err != nil {
    xlog.Fatal(err)
} else {
    xlog.AddListener(w2f)
}

xlog.Info("server start...")
xlog.Debugf("ip : %v", "127.0.0.1")

Features

###Level logging

// xlog provide 6 logging levels.
const (
	PanicLevel Level = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
)

you can call 'SetLevel' to change the log level. All the logs which level <= your set will be output. for example:

// all logs will be output because DEBUG is the max level.
xlog.SetLevel(xlog.DebugLevel) 

// only Panic/Fatal/Error logs will be output because WARN/INFO/DEBUG > ERROR.
xlog.SetLevel(xlog.ErrorLevel)

###Custom Log Layout xlog provide a flexible log layout system to custom the style of log output. What you need to do is just set the layout flags.

xlog.SetLayout('layout flags...')

xlog provide some builtin layout:

//   %y : year
//   %M : month
//   %d : day
//   %h : hour
//   %m : min
//   %s : second
//   %l : log msg
//   %L : log level
//   %F : file			eg: /a/b/c/d.go
//   %f : short file	eg: d.go
//   %i : line
//   %D : %y/%M/%d
//   %T : %h:%m:%s

You can use a combination of them, for example:

// this mean every log message will have a '[level] year/month/day hour:min:sec' perfix, eg:
xlog.SetLayout("%L %D %T %l")

// outputs:
[INFO] 2016/01/01 13:27:07 net start...
[WARN] 2016/01/01 13:28:00 ...
[DEBUG] 2016/01/01 13:28:00 accept...

// add filename and line to log message.
xlog.SetLayout("%L %D %T [%f(%i)] %l")

// outputs:
[INFO] 2016/01/01 13:27:07 [test.go:(72)] net start...
[WARN] 2016/01/01 13:28:00 [test.go:(100)] ...
[DEBUG] 2016/01/01 13:28:00 [test.go:(128)] accept...

You can use any form of combination, even meaningless thing, such as more spaces, arbitrary symbols:

xlog.SetLayout("hahaha%L | %D   %T [ABC] %l [i'm after hahaha]")

// outputs:
// notice the prefix 'hahaha', the spaces in the middle, and the suffix '[i'm after hahaha]'
hahaha[INFO] | 2017/01/07     14:09:47 [ABC] net start... [i'm after hahaha]
hahaha[WARN] | 2017/01/07     14:09:47 [ABC] ... [i'm after hahaha]
hahaha[DEBUG] | 2017/01/07     14:09:47 [ABC] accept... [i'm after hahaha]

NOTICE: If you doesn't call 'SetLayout', xlog will use '%L %D %T %l' by default.

###Output a log to different targets xlog use listener system to output the log message.

// A Listener simple typed of io.Writer
type Listener io.Writer

A logger can have multiple listeners, xlog have 2 builtin listener, which are os.Stderr and W2FileListener. xlog will output log to os.Stderr by default, but you can add W2FileListener to output the log to file.

w2f, err := xlog.NewW2FileListener("logfilePath...")
if err != nil {
    xlog.Fatal(err)
} else {
    xlog.AddListener(w2f)
}

In 'NewW2FileListener' function, xlog will use the 'logfilePath' to create log file, so please makesure your path is correct.

os.MkdirAll(filepath.Dir(logfilePath), os.ModePerm)

Also, you can give a empty path to NewW2FileListener(""), this will create log file by simple rule. for example: If your app current path is 'a/b/c', and your app name is 'testapp' Then the log file will be 'a/b/c/log/testapp_2016_01_01.log'

w2f, err := xlog.NewW2FileListener("")  // create log file at : 'a/b/c/log/test_2016_01_01.log'
if err != nil {
    xlog.Fatal(err)
}
xlog.AddListener(w2f)

You can create new listener according you need, just implement the io.Writer interface.

type Writer interface {
	Write(p []byte) (n int, err error)
}

###Thread safety By default xlog is protected by mutex, so you can output logs in multiple goroutines.

Documentation

Overview

Package xlog implements a simple logging package.

The Logger provide some methods for formatting log message output and log filter by set log level. The Layouter used to format the log message according to the format you want.

It also has a predefined 'standard' Logger accessible through helper functions which are easier to use than creating a Logger manually.

The Fatal[f] functions call os.Exit(1) after writing the log message. The Panic[f] functions call panic after writing the log message.

Index

Constants

View Source
const DefaultLoggerLayout = "%L %D %T %l"

DefaultLoggerLayout give the default log layout. "%L %D %T %l" mean "[INFO] 2017/01/05 18:02:17 some log msg..." See Layouter for details.

Variables

View Source
var Level2Str = []string{
	"PANIC",
	"FATAL",
	"ERROR",
	"WARN",
	"INFO",
	"DEBUG",
}

Level2Str used to conver Level value to string.

Functions

func AddListener

func AddListener(lis Listener) bool

AddListener is equivalent to Logger.AddListener.

func Close

func Close() error

Close is use to close the logger

func Debug

func Debug(v ...interface{})

Debug is equivalent to Logger.Debug.

func Debugf

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

Debugf is equivalent to Logger.Debugf.

func Error

func Error(v ...interface{})

Error is equivalent to Logger.Error.

func Errorf

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

Errorf is equivalent to Logger.Errorf.

func Fatal

func Fatal(v ...interface{})

Fatal is equivalent to Logger.Fatal.

func Fatalf

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

Fatalf is equivalent to Logger.Fatalf.

func Info

func Info(v ...interface{})

Info is equivalent to Logger.Info.

func Infof

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

Infof is equivalent to Logger.Infof.

func Log

func Log(level Level, v ...interface{})

Log is equivalent to Logger.Log.

func Logf

func Logf(level Level, format string, v ...interface{})

Logf is equivalent to Logger.Logf.

func Panic

func Panic(v ...interface{})

Panic is equivalent to Logger.Panic.

func Panicf

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

Panicf is equivalent to Logger.Panicf.

func ParseAndSetLevel

func ParseAndSetLevel(lev string) error

func RemoveListener

func RemoveListener(lis Listener) bool

RemoveListener is equivalent to Logger.RemoveListener.

func SetLayout

func SetLayout(layout string)

SetLayout is equivalent to Logger.SetLayout.

func SetLevel

func SetLevel(lev Level)

SetLevel is equivalent to Logger.SetLevel.

func Warn

func Warn(v ...interface{})

Warn is equivalent to Logger.Warn.

func Warnf

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

Warnf is equivalent to Logger.Warnf.

Types

type Layouter

type Layouter interface {
	// contains filtered or unexported methods
}

Layouter used to format log message.

  %y : year
  %M : month
  %d : day
  %h : hour
  %m : min
  %s : second
  %l : log msg
  %L : log level
  %F : file			eg: /a/b/c/d.go
	 %f : short file	eg: d.go
  %i : line
  %D : %y/%M/%d
  %T : %h:%m:%s

type Level

type Level uint8

Level used to filter log message by the Logger.

const (
	PanicLevel Level = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
)

logging levels.

func ParseLevel

func ParseLevel(str string) (Level, bool)

ParseLevel used to parse string to Level value. It will return (ParsedLevel, true) if parse successed, otherwise will return (InfoLevel, false).

type Listener

type Listener io.WriteCloser

A Listener simple typed of io.Writer

type Logger

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

A Logger represents an active logging object that generates lines of output to log listeners. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

func New

func New(lev Level, lis Listener, layout string) *Logger

New creates a new Logger.

func (*Logger) AddListener

func (l *Logger) AddListener(lis Listener) bool

AddListener add a listener to the Logger, return false if the listener existed already, otherwise return true.

func (*Logger) Close

func (l *Logger) Close() error

func (*Logger) Debug

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

Debug print a DebugLevel message to the logger. Arguments are handled in the manner of fmt.Print.

func (*Logger) Debugf

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

Debugf print a DebugLevel message to the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Error

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

Error print a ErrorLevel message to the logger. Arguments are handled in the manner of fmt.Print.

func (*Logger) Errorf

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

Errorf print a ErrorLevel message to the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Fatal

func (l *Logger) Fatal(v ...interface{})

Fatal print a FatalLevel message to the logger followed by a call to os.Exit(1). Arguments are handled in the manner of fmt.Print.

func (*Logger) Fatalf

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

Fatalf print a FatalLevel message to the logger followed by a call to os.Exit(1). Arguments are handled in the manner of fmt.Printf.

func (*Logger) Info

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

Info print a InfoLevel message to the logger. Arguments are handled in the manner of fmt.Print.

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof print a InfoLevel message to the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Log

func (l *Logger) Log(level Level, msg string)

Log print a leveled message to the logger. Arguments are handled in the manner of fmt.Print.

func (*Logger) Panic

func (l *Logger) Panic(v ...interface{})

Panic print a PanicLevel message to the logger followed by a call to panic(). Arguments are handled in the manner of fmt.Print.

func (*Logger) Panicf

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

Panicf print a PanicLevel message to the logger followed by a call to panic(). Arguments are handled in the manner of fmt.Printf.

func (*Logger) RemoveAllListeners

func (l *Logger) RemoveAllListeners()

RemoveAllListeners remove all listeners from the logger.

func (*Logger) RemoveListener

func (l *Logger) RemoveListener(lis Listener) bool

RemoveListener remove a listener from the Logger, return true if remove success, otherwise return false.

func (*Logger) SetLayout

func (l *Logger) SetLayout(layout string)

SetLayout set the layout of log message. will use DefaultLoggerLayout by default if layout parameter if empty. see Layouter for details.

func (*Logger) SetLevel

func (l *Logger) SetLevel(lev Level)

SetLevel set the log level for Logger.

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn print a WarnLevel message to the logger. Arguments are handled in the manner of fmt.Print.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...interface{})

Warnf print a WarnLevel message to the logger. Arguments are handled in the manner of fmt.Printf.

type W2FileListener

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

W2FileListener use to output log to file.

func NewW2FileListener

func NewW2FileListener(filePath string) (*W2FileListener, error)

NewW2FileListener creates a new W2FileListener. If filePath is empty, then will create file at appPath/Log/

func (*W2FileListener) Close

func (l *W2FileListener) Close() error

Close is equivalent to os.File.Close.

func (*W2FileListener) Write

func (l *W2FileListener) Write(p []byte) (n int, err error)

Write is equivalent to os.File.Write.

Jump to

Keyboard shortcuts

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