nxlog4go

package module
v2.0.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2020 License: BSD-2-Clause Imports: 14 Imported by: 2

README

nxlog4go - Next logging package based on log4go

License GoDoc Build Status Maintainability

Installation

  • Run go get github.com/ccpaging/nxlog4go

OR

  • Run go install github.com/ccpaging/nxlog4go

Features:

  • Structured
  • Fast - see benchmark
  • Extendable 3rd appender
  • Configurable
  • Robust
  • Completely API compatible with the stdlib log - support ansi color term
  • Logging With data fields - like uber zap
  • No external dependencies - plain ol' Go stdlib

Usage:

  • Add the following import:

import log "github.com/ccpaging/nxlog4go"

  • Sample, using global log
package main

import (
    log "github.com/ccpaging/nxlog4go"
)

func main() {
    log.Debug("This is Debug")
    log.Info("This is Info")
}

Acknowledgements:

Stability

This package is a work still in progress.

In any event, I encourage you to send me feedback.

But I really wouldn't recommend using nxlog4go in factory environment just yet.

Documentation

Index

Examples

Constants

View Source
const (
	FINEST int = iota
	FINE
	DEBUG
	TRACE
	INFO
	WARN
	ERROR
	CRITICAL
)

logging levels used by the logger

View Source
const (
	Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
	Ltime                         // the time in the local time zone: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

These flags define which text to prefix to each log entry generated by the Logger. Bits are or'ed together to control what's printed. There is no control over the order they appear (the order listed here) or the format they present (as described in the comments). The prefix is followed by a colon only when Llongfile or Lshortfile is specified. For example, flags Ldate | Ltime (or LstdFlags) produce,

2009/01/23 01:23:23 message

while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,

2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
View Source
const (
	Version = "nxlog4go-v2.0.3"
	Major   = 2
	Minor   = 0
	Build   = 3
)

Version information

Variables

View Source
var FormatLogLog = "%T %P %L %M"

FormatLogLog is format for internal log

Functions

func Critical

func Critical(arg0 interface{}, args ...interface{}) error

Critical is a wrapper for (*Logger).Critical

func Debug

func Debug(arg0 interface{}, args ...interface{})

Debug is a wrapper for (*Logger).Debug

func Error

func Error(arg0 interface{}, args ...interface{}) error

Error is a wrapper for (*Logger).Error

func Fatal

func Fatal(v ...interface{})

Fatal is equivalent to Print() followed by a call to os.Exit(1).

func Fatalf

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

Fatalf is equivalent to Printf() followed by a call to os.Exit(1).

func Fatalln

func Fatalln(v ...interface{})

Fatalln is equivalent to Println() followed by a call to os.Exit(1).

func Fine

func Fine(arg0 interface{}, args ...interface{})

Fine is a wrapper for (*Logger).Fine

func Finest

func Finest(arg0 interface{}, args ...interface{})

Finest is a wrapper for (*Logger).Finest

func Flags

func Flags() int

Flags returns the output flags for the standard logger.

func Info

func Info(arg0 interface{}, args ...interface{})

Info is a wrapper for (*Logger).Info

func LogLogDebug

func LogLogDebug(arg0 interface{}, args ...interface{})

LogLogDebug logs a message at the debug log level.

func LogLogError

func LogLogError(arg0 interface{}, args ...interface{}) error

LogLogError logs a message at the error log level.

func LogLogInfo

func LogLogInfo(arg0 interface{}, args ...interface{})

LogLogInfo logs a message at the info log level.

func LogLogTrace

func LogLogTrace(arg0 interface{}, args ...interface{})

LogLogTrace logs a message at the trace log level.

func LogLogWarn

func LogLogWarn(arg0 interface{}, args ...interface{}) error

LogLogWarn logs a message at the warn log level.

func NewBeginColorizer

func NewBeginColorizer(typ string) patt.Encoder

NewBeginColorizer creates a new color begin encoder.

func NewEndColorizer

func NewEndColorizer(typ string) patt.Encoder

NewEndColorizer creates a new color reset encoder.

func NewLevelEncoder added in v1.0.4

func NewLevelEncoder(typ string) patt.Encoder

NewLevelEncoder creates a new level encoder.

func NewStdLog

func NewStdLog(e *Entry) *log.Logger

NewStdLog returns a *log.Logger which writes to the supplied logger Entry at Info Level.

func NewStdLogAt

func NewStdLogAt(e *Entry, level interface{}) *log.Logger

NewStdLogAt returns *log.Logger which writes to supplied logger Entry at required level.

func Output

func Output(calldepth int, s string) error

Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is the count of the number of frames to skip when computing the file name and line number if Llongfile or Lshortfile is set; a value of 1 will print the details for the caller of Output.

func Panic

func Panic(v ...interface{})

Panic is equivalent to Print() followed by a call to panic().

func Panicf

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

Panicf is equivalent to Printf() followed by a call to panic().

func Panicln

func Panicln(v ...interface{})

Panicln is equivalent to Println() followed by a call to panic().

func Prefix

func Prefix() string

Prefix returns the output prefix for the standard logger.

func Print

func Print(v ...interface{})

Print calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Print.

func Printf

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

Printf calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Printf.

func Println

func Println(v ...interface{})

Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println.

func RedirectStdLog

func RedirectStdLog(e *Entry) func()

RedirectStdLog redirects output from the standard library's package-global logger to the supplied logger at InfoLevel. Since zap already handles caller annotations, timestamps, etc., it automatically disables the standard library's annotations and prefixing.

It returns a function to restore the original prefix and flags and reset the standard library's output to os.Stderr.

func RedirectStdLogAt

func RedirectStdLogAt(e *Entry, level interface{}) func()

RedirectStdLogAt redirects output from the standard library's package-global logger to the supplied logger at the specified level. Since zap already handles caller annotations, timestamps, etc., it automatically disables the standard library's annotations and prefixing.

It returns a function to restore the original prefix and flags and reset the standard library's output to os.Stderr.

func SetFlags

func SetFlags(flag int)

SetFlags sets the output flags for the standard logger.

func SetOutput

func SetOutput(w io.Writer)

SetOutput sets the output destination for the standard logger.

func SetPrefix

func SetPrefix(prefix string)

SetPrefix sets the output prefix for the standard logger.

func Trace

func Trace(arg0 interface{}, args ...interface{})

Trace is a wrapper for (*Logger).Trace

func Warn

func Warn(arg0 interface{}, args ...interface{}) error

Warn is a wrapper for (*Logger).Warn

func Writer

func Writer() io.Writer

Writer returns the output destination for the standard logger.

Types

type Entry added in v1.0.1

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

A Entry contains all of the pertinent information for each message It is the final or intermediate logging entry also. It contains all the fields passed with prefix and With(key, value ...). It's finally logged when Trace, Debug, Info, Warn, Error, Critical called on it.

func NewEntry added in v1.0.1

func NewEntry(l *Logger) *Entry

NewEntry creates a new logging entry with a logger

func (*Entry) AddCallerSkip

func (e *Entry) AddCallerSkip(addSkip int) *Entry

AddCallerSkip increases the number of callers skipped by caller annotation. When building wrappers around the logger Entry, supplying this function to reporting the caller's caller information of the wrapper code.

func (*Entry) Critical added in v1.0.1

func (e *Entry) Critical(arg0 interface{}, args ...interface{})

Critical logs a message at the critical log level and returns the formatted error, See Warn for an explanation of the performance and Debug for an explanation of the parameters.

func (*Entry) Debug added in v1.0.1

func (e *Entry) Debug(arg0 interface{}, args ...interface{})

Debug is a utility method for debug log messages. The behavior of Debug depends on the first argument:

  • arg0 is a string When given a string as the first argument, this behaves like Logf but with the DEBUG log level: the first argument is interpreted as a format for the latter arguments.
  • arg0 is a func()string When given a closure of type func()string, this logs the string returned by the closure iff it will be logged. The closure runs at most one time.
  • arg0 is interface{} When given anything else, formatted as string (ala Sprint).

func (*Entry) Error added in v1.0.1

func (e *Entry) Error(arg0 interface{}, args ...interface{})

Error logs a message at the error log level and returns the formatted error, See Warn for an explanation of the performance and Debug for an explanation of the parameters.

func (*Entry) Fine added in v1.0.1

func (e *Entry) Fine(arg0 interface{}, args ...interface{})

Fine logs a message at the fine log level. See Debug for an explanation of the arguments.

func (*Entry) Finest added in v1.0.1

func (e *Entry) Finest(arg0 interface{}, args ...interface{})

Finest logs a message at the finest log level. See Debug for an explanation of the arguments.

func (*Entry) Info added in v1.0.1

func (e *Entry) Info(arg0 interface{}, args ...interface{})

Info logs a message at the info log level. See Debug for an explanation of the arguments.

func (*Entry) Log added in v1.0.1

func (e *Entry) Log(calldepth int, level int, arg0 interface{}, args ...interface{})

Log sends a log message with level, and message. Call depth:

2 - Where calling the wrapper of entry.Log(...)
1 - Where calling entry.Log(...)
0 - Where internal calling entry.flush()

func (*Entry) SetPrefix

func (e *Entry) SetPrefix(prefix string) *Entry

SetPrefix sets the output prefix for the entry.

func (*Entry) Trace added in v1.0.1

func (e *Entry) Trace(arg0 interface{}, args ...interface{})

Trace logs a message at the trace log level. See Debug for an explanation of the arguments.

func (*Entry) Warn added in v1.0.1

func (e *Entry) Warn(arg0 interface{}, args ...interface{})

Warn logs a message at the warn log level and returns the formatted error. At the warn level and higher, there is no performance benefit if the message is not actually logged, because all formats are processed and all closures are executed to format the error message. See Debug for further explanation of the arguments.

func (*Entry) With added in v1.0.1

func (e *Entry) With(args ...interface{}) *Entry

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

func (*Entry) WithMore added in v1.0.4

func (e *Entry) WithMore(args ...interface{}) *Entry

WithMore appends name-value pairs to the log entry.

type FilterConfig

type FilterConfig struct {
	Enabled    string      `xml:"enabled,attr" json:"enabled"`
	Tag        string      `xml:"tag" json:"tag"`
	Type       string      `xml:"type" json:"type"`
	Dsn        string      `xml:"dsn" json:"dsn"`
	Level      string      `xml:"level" json:"level"`
	Properties []NameValue `xml:"property" json:"properties"`
}

FilterConfig offers a declarative way to construct a logger's default writer, internal log and 3rd appenders

type Level

type Level int

Level is the integer logging levels

func (Level) Int added in v1.0.1

func (l Level) Int(v interface{}) int

Int casts an interface to a level int.

func (Level) IntE

func (l Level) IntE(v interface{}) (int, error)

IntE casts an interface to a level int.

func (Level) String

func (l Level) String() string

String return the string of integer Level

type Logger

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

A Logger represents an active logging object that generates lines of output to an io.Writer, and a collection of Filters through which log messages are written. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

Example
package main

import (
	"bytes"
	"fmt"

	log "github.com/ccpaging/nxlog4go"
)

func main() {
	var (
		buf    bytes.Buffer
		logger = log.New(&buf, "logger: ", log.Lshortfile)
	)

	logger.Print("Hello, log file!")

	fmt.Print(&buf)
}
Output:

logger: example_test.go:19: Hello, log file!

func GetLogLog

func GetLogLog() *Logger

GetLogLog creates internal logger if not existed, and returns it. This logger used to output log statements from within the package. Do not set any filters.

func GetLogger

func GetLogger() *Logger

GetLogger returns the default logger.

func New

func New(out io.Writer, prefix string, flag int) *Logger

New creates a new Logger. The out variable sets the destination to which log data will be written. The prefix appears at the beginning of each generated log line. The flag argument defines the logging properties.

func NewLogger

func NewLogger(level int) *Logger

NewLogger creates a new logger with a "stderr" writer to send formatted log messages at or above level to standard output.

func (*Logger) AddFilter

func (l *Logger) AddFilter(name string, level int, apps ...driver.Appender) *Logger

AddFilter adds the named appenders to the Logger which will only log messages at or above level. This function should not be called from multiple goroutines.

Returns the logger for chaining.

func (*Logger) Attach

func (l *Logger) Attach(filters ...*driver.Filter) *Logger

Attach adds the filters to logger.

func (*Logger) Clone

func (l *Logger) Clone() *Logger

Clone creates a new clone logger.

 New logger can be used in different module.
	Using owner prefix and runtime caller switch.
 Running in the parallel go routines and packages is safe.

func (*Logger) Close added in v1.0.4

func (l *Logger) Close()

Close closes all log filters in preparation for exiting the program. Calling this is not really imperative, unless you want to guarantee that all log messages are written.

Notice: Close() removes all filters (and thus all appenders) except "stdout" from the logger.

func (*Logger) Copy

func (l *Logger) Copy(src *Logger)

Copy copies a logger except prefix and caller switch.

func (*Logger) Critical

func (l *Logger) Critical(arg0 interface{}, args ...interface{}) error

Critical logs a message at the critical log level and returns the formatted error, See Warn for an explanation of the performance and ArgsToString for an explanation of the parameters.

func (*Logger) Debug

func (l *Logger) Debug(arg0 interface{}, args ...interface{})

Debug is a utility method for debug log messages. See ArgsToString for an explanation of the arguments.

func (*Logger) Detach

func (l *Logger) Detach(filters ...*driver.Filter) *Logger

Detach removes the filters from logger.

func (*Logger) Dispatch

func (l *Logger) Dispatch(r *driver.Recorder)

Dispatch encodes a log recorder to bytes and writes it.

func (*Logger) Enable

func (l *Logger) Enable(enable bool) *Logger

Enable sets the standard filter's Enabler to deny all, or restores the default at/above level enabler.

func (*Logger) Error

func (l *Logger) Error(arg0 interface{}, args ...interface{}) error

Error logs a message at the error log level and returns the formatted error, See Warn for an explanation of the performance and ArgsToString for an explanation of the parameters.

func (*Logger) Fatal

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

Fatal is equivalent to l.Print() followed by a call to os.Exit(1).

func (*Logger) Fatalf

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

Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).

func (*Logger) Fatalln

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

Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).

func (*Logger) Filters

func (l *Logger) Filters() map[string]*driver.Filter

Filters returns the output filters for the logger.

func (*Logger) Fine

func (l *Logger) Fine(arg0 interface{}, args ...interface{})

Fine logs a message at the fine log level. See Debug for an explanation of the arguments.

func (*Logger) Finest

func (l *Logger) Finest(arg0 interface{}, args ...interface{})

Finest logs a message at the finest log level. See Debug for an explanation of the arguments.

func (*Logger) Flags

func (l *Logger) Flags() int

Flags returns the output flags for the logger.

func (*Logger) Info

func (l *Logger) Info(arg0 interface{}, args ...interface{})

Info logs a message at the info log level. See Debug for an explanation of the arguments.

func (*Logger) Layout

func (l *Logger) Layout() driver.Layout

Layout returns the output layout for the logger.

func (*Logger) LoadConfiguration

func (l *Logger) LoadConfiguration(lc *LoggerConfig) (errs []error)

LoadConfiguration sets options of logger, and creates/loads/sets appenders.

func (*Logger) Log

func (l *Logger) Log(calldepth int, level int, arg0 interface{}, args ...interface{})

Log sends a log message with level and message. Call depth:

2 - Where calling the wrapper of logger.Log(...)
1 - Where calling logger.Log(...)
0 - Where internal calling entry.flush()

func (*Logger) Output

func (l *Logger) Output(calldepth int, s string) error

Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is used to recover the PC and is provided for generality, although at the moment on all pre-defined paths it will be 2.

Example
package main

import (
	"bytes"
	"fmt"

	log "github.com/ccpaging/nxlog4go"
)

func main() {
	var (
		buf    bytes.Buffer
		logger = log.New(&buf, "INFO: ", log.Lshortfile)

		infof = func(info string) {
			logger.Output(2, info)
		}
	)

	infof("Hello world")

	fmt.Print(&buf)
}
Output:

INFO: example_test.go:36: Hello world

func (*Logger) Panic

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

Panic is equivalent to l.Print() followed by a call to panic().

func (*Logger) Panicf

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

Panicf is equivalent to l.Printf() followed by a call to panic().

func (*Logger) Panicln

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

Panicln is equivalent to l.Println() followed by a call to panic().

func (*Logger) Prefix

func (l *Logger) Prefix() string

Prefix returns the output prefix for the logger.

func (*Logger) Print

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

Print calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Print.

func (*Logger) Printf

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

Printf calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Println

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

Println calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Println.

func (*Logger) Set

func (l *Logger) Set(k string, v interface{}) (err error)

Set sets name-value option with:

prefix - The output prefix
caller - Enable or disable the runtime caller function
level  - The output level

layout options...

Return errors.

func (*Logger) SetFilters

func (l *Logger) SetFilters(filters map[string]*driver.Filter) *Logger

SetFilters sets the output filters for the logger.

func (*Logger) SetFlags

func (l *Logger) SetFlags(flag int) *Logger

SetFlags sets the output flags for the logger.

func (*Logger) SetLayout

func (l *Logger) SetLayout(layout driver.Layout) *Logger

SetLayout sets the output layout for the logger.

func (*Logger) SetOptions

func (l *Logger) SetOptions(args ...interface{}) *Logger

SetOptions sets name-value pair options.

Return *Logger.

func (*Logger) SetOutput

func (l *Logger) SetOutput(w io.Writer) *Logger

SetOutput sets the output destination for the logger.

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(prefix string) *Logger

SetPrefix sets the output prefix for the logger.

func (*Logger) Trace

func (l *Logger) Trace(arg0 interface{}, args ...interface{})

Trace logs a message at the trace log level. See ArgsToString for an explanation of the arguments.

func (*Logger) Warn

func (l *Logger) Warn(arg0 interface{}, args ...interface{}) error

Warn logs a message at the warn log level and returns the formatted error. At the warn level and higher, there is no performance benefit if the message is not actually logged, because all formats are processed and all closures are executed to format the error message. See ArgsToString for further explanation of the arguments.

func (*Logger) With added in v0.9.4

func (l *Logger) With(args ...interface{}) *Entry

With creates a child logger and adds structured context to it. Args added to the child don't affect the parent, and vice versa.

func (*Logger) Writer

func (l *Logger) Writer() io.Writer

Writer returns the output destination for the logger.

type LoggerConfig

type LoggerConfig struct {
	Version string          `xml:"version,attr" json:"version"`
	Filters []*FilterConfig `xml:"filter" json:"filters"`
}

LoggerConfig offers a declarative way to construct a logger. See examples/config.xml and examples/config.json for documentation

type NameValue

type NameValue struct {
	Name  string `xml:"name,attr" json:"name"`
	Value string `xml:",chardata" json:"value"`
}

NameValue stores every single option's name and value.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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