Documentation ¶
Overview ¶
Package xylog is designed for leveled and structured logging, dynamic fields, high performance, zone management, simple configuration, and readable syntax.
Index ¶
- Constants
- func AddLevel(level int, levelName string)
- func CheckLevel(level int) int
- func Flush()
- func GetLevelName(level int) string
- func SetFindCaller(b bool)
- func SetSkipCall(skip int)
- func SetTimeLayout(layout string)
- type Emitter
- type EventLogger
- func (e *EventLogger) Critical()
- func (e *EventLogger) Debug()
- func (e *EventLogger) Error()
- func (e *EventLogger) Fatal()
- func (e *EventLogger) Field(key string, value any) *EventLogger
- func (e *EventLogger) Info()
- func (e *EventLogger) Log(level int)
- func (e *EventLogger) Panic()
- func (e *EventLogger) Warn()
- func (e *EventLogger) Warning()
- type Filter
- type Handler
- func (h *Handler) AddEmitter(e Emitter)
- func (h *Handler) AddField(name string, value any)
- func (h *Handler) AddFilter(f Filter)
- func (h *Handler) AddMacro(name, macro string)
- func (h *Handler) Emitters() []Emitter
- func (h *Handler) Filters() []Filter
- func (h *Handler) Handle(record LogRecord)
- func (h *Handler) Level() int
- func (h *Handler) Name() string
- func (h *Handler) RemoveEmitter(e Emitter)
- func (h *Handler) RemoveFilter(f Filter)
- func (h *Handler) SetEncoding(e encoding.Encoding)
- func (h *Handler) SetLevel(level int)
- type LogRecord
- type Logger
- func (lg *Logger) AddField(key string, value any)
- func (lg *Logger) AddFilter(f Filter)
- func (lg *Logger) AddHandler(h *Handler)
- func (lg *Logger) Children() []*Logger
- func (lg *Logger) Critical(s string)
- func (lg *Logger) Criticalf(s string, a ...any)
- func (lg *Logger) Debug(s string)
- func (lg *Logger) Debugf(s string, a ...any)
- func (lg *Logger) Error(s string)
- func (lg *Logger) Errorf(s string, a ...any)
- func (lg *Logger) Event(e string) *EventLogger
- func (lg *Logger) Fatal(s string)
- func (lg *Logger) Fatalf(s string, a ...any)
- func (lg *Logger) Filters() []Filter
- func (lg *Logger) Handlers() []*Handler
- func (lg *Logger) Info(s string)
- func (lg *Logger) Infof(s string, a ...any)
- func (lg *Logger) Level() int
- func (lg *Logger) Log(level int, s string)
- func (lg *Logger) Logf(level int, s string, a ...any)
- func (lg *Logger) Name() string
- func (lg *Logger) Panic(s string)
- func (lg *Logger) Panicf(s string, a ...any)
- func (lg *Logger) Parent() *Logger
- func (lg *Logger) RemoveAllHandlers()
- func (lg *Logger) RemoveFilter(f Filter)
- func (lg *Logger) RemoveHandler(h *Handler)
- func (lg *Logger) SetLevel(level int)
- func (lg *Logger) Stack(level int)
- func (lg *Logger) Warn(s string)
- func (lg *Logger) Warnf(s string, a ...any)
- func (lg *Logger) Warning(s string)
- func (lg *Logger) Warningf(s string, a ...any)
- type SimpleConfig
- type StreamEmitter
Examples ¶
Constants ¶
const ( NOTLOG = 1000 CRITICAL = 50 ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 )
Default levels, these can be replaced with any positive set of values having corresponding names. There is a pseudo-level, NOTSET, which is only really there as a lower limit for user-defined levels. Handlers and loggers are initialized with NOTSET so that they will log all messages, even at user-defined levels.
Variables ¶
This section is empty.
Functions ¶
func AddLevel ¶
AddLevel associates a log level with name. It can overwrite other log levels. Default log levels:
NOTSET 0 DEBUG 10 INFO 20 WARN/WARNING 30 ERROR/FATAL 40 CRITICAL 50
func CheckLevel ¶ added in v0.2.0
CheckLevel validates if the given level is associated or not.
func GetLevelName ¶ added in v0.2.0
GetLevelName returns a name associated with the given level.
func SetFindCaller ¶ added in v0.2.0
func SetFindCaller(b bool)
SetFindCaller with true to find caller information including filename, line number, function name, and module.
func SetSkipCall ¶
func SetSkipCall(skip int)
SetSkipCall sets the new skipCall value which dertermine the depth call of Logger.log method.
func SetTimeLayout ¶
func SetTimeLayout(layout string)
SetTimeLayout sets the time layout to print asctime. It is time.RFC3339Nano by default.
Types ¶
type Emitter ¶
type Emitter interface { // Emit will be called after a record was decided to log. Emit([]byte) // Flush writes unflushed buffered data to destination, then closes the // Emitter. Flush() }
Emitter instances dispatch logging events to specific destinations.
type EventLogger ¶
type EventLogger struct {
// contains filtered or unexported fields
}
EventLogger is a logger wrapper supporting to compose logging message with key-value structure.
Example ¶
package main import ( "os" "github.com/xybor-x/xylog" ) func main() { var emitter = xylog.NewStreamEmitter(os.Stdout) var handler = xylog.GetHandler("") handler.AddEmitter(emitter) var logger = xylog.GetLogger("example.EventLogger") defer xylog.Flush() logger.AddHandler(handler) logger.SetLevel(xylog.DEBUG) logger.Event("create").Field("product", 1235).Debug() }
Output: event=create product=1235
func (*EventLogger) Critical ¶
func (e *EventLogger) Critical()
Critical calls Log with CRITICAL level.
func (*EventLogger) Fatal ¶
func (e *EventLogger) Fatal()
Fatal calls Log with CRITICAL level, then followed by a call to os.Exit(1).
func (*EventLogger) Field ¶
func (e *EventLogger) Field(key string, value any) *EventLogger
Field adds a key-value pair to logging message.
func (*EventLogger) Panic ¶ added in v0.5.0
func (e *EventLogger) Panic()
Panic calls Log with CRITICAL level, then followed by a call to panic().
type Filter ¶
Filter instances are used to perform arbitrary filtering of LogRecord.
Example ¶
package main import ( "os" "github.com/xybor-x/xylog" "github.com/xybor-x/xylog/test" ) func main() { var emitter = xylog.NewStreamEmitter(os.Stdout) var handler = xylog.GetHandler("") handler.AddEmitter(emitter) handler.AddFilter(&test.LoggerNameFilter{Name: "example.filter.chat"}) var logger = xylog.GetLogger("example.filter") defer xylog.Flush() logger.AddHandler(handler) logger.SetLevel(xylog.DEBUG) xylog.GetLogger("example.filter.auth").Debug("auth foo") xylog.GetLogger("example.filter.chat").Debug("chat foo") }
Output: messsage="chat foo"
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles logging events. Do NOT instantiated directly this struct.
Any Handler with a not-empty name will be associated with its name.
Example ¶
package main import ( "fmt" "github.com/xybor-x/xylog" ) func main() { // You can use a Handler throughout program because all Handlers can be // identified by their names. var handlerA = xylog.GetHandler("example.Handler") var handlerB = xylog.GetHandler("example.Handler") if handlerA == handlerB { fmt.Println("handlerA == handlerB") } else { fmt.Println("handlerA != handlerB") } // In case the name is an empty string, it creates different Handlers every // call. var handlerC = xylog.GetHandler("") var handlerD = xylog.GetHandler("") if handlerC == handlerD { fmt.Println("handlerC == handlerD") } else { fmt.Println("handlerC != handlerD") } }
Output: handlerA == handlerB handlerC != handlerD
func GetHandler ¶
GetHandler gets a handler with the specified name, creating it if it doesn't yet exist.
Leave the name as empty if you want to create an anonymous Handler.
func (*Handler) AddEmitter ¶ added in v0.2.0
AddEmitter adds a specified Emitter.
func (*Handler) AddMacro ¶ added in v0.2.0
AddMacro adds the macro value to the logging message under a name.
func (*Handler) Handle ¶ added in v0.2.0
Handle checks if a record should be logged or not, then calls Emitters if it is.
func (*Handler) Name ¶ added in v0.2.0
Name returns the current name. An anonymous Handler returns the empty name.
func (*Handler) RemoveEmitter ¶ added in v0.2.0
RemoveEmitter remove an existed Emitter.
func (*Handler) RemoveFilter ¶
RemoveFilter remove an existed Filter.
func (*Handler) SetEncoding ¶ added in v0.2.0
SetEncoding sets a new Encoding.
type LogRecord ¶
type LogRecord struct { // Textual time when the LogRecord was created. Asctime string // Time when the LogRecord was created (time.Now().Unix() return value). Created int64 // This a not a macro. Fields are always added to the logging message // without calling AddMacro. Fields []field // Filename is the portion of pathname. FileName string // Funcname is the name of function which logged the record. FuncName string // Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", // "CRITICAL"). LevelName string // Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, // CRITICAL). LevelNo int // Source line number where the logging call was issued. LineNo int // The module called log method. Module string // Millisecond portion of the creation time. Msecs int // Name of the logger. Name string // Full pathname of the source file where the logging call was issued. PathName string // Process ID. Process int // Time in milliseconds when the LogRecord was created, relative to the time // the logging module was loaded (typically at application startup time). RelativeCreated int64 }
A LogRecord instance represents an event being logged.
LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is Message. The record also includes information as when the record was created or the source line where the logging call was made.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger represents a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods. So in the instance given above, channel names might be "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting.
Example ¶
package main import ( "os" "github.com/xybor-x/xylog" ) func main() { var emitter = xylog.NewStreamEmitter(os.Stdout) var handler = xylog.GetHandler("") handler.AddEmitter(emitter) var logger = xylog.GetLogger("example.Logger") defer xylog.Flush() logger.AddHandler(handler) logger.SetLevel(xylog.DEBUG) logger.Debugf("foo %s", "bar") }
Output: messsage="foo bar"
func GetLogger ¶
GetLogger gets a logger with the specified name, creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c", or similar.
Leave name as empty string to get the root logger.
func (*Logger) AddField ¶ added in v0.1.0
AddField adds a fixed field to all logging message of this logger.
func (*Logger) Event ¶
func (lg *Logger) Event(e string) *EventLogger
Event creates an EventLogger which logs key-value pairs.
func (*Logger) Fatal ¶
Fatal logs default formatting objects with CRITICAL level, then followed by a call to os.Exit(1).
func (*Logger) Fatalf ¶
Fatalf logs a formatting message with CRITICAL level, then followed by a call to os.Exit(1).
func (*Logger) Panic ¶ added in v0.5.0
Panic logs default formatting objects with CRITICAL level, then followed by a call to panic().
func (*Logger) Panicf ¶ added in v0.5.0
Panicf logs a formatting message with CRITICAL level, then followed by a call to panic().
func (*Logger) Parent ¶ added in v0.2.0
Parent returns the parent logger. If there is no parent, return nil instead.
func (*Logger) RemoveAllHandlers ¶ added in v0.2.0
func (lg *Logger) RemoveAllHandlers()
RemoveAllHandlers removes all existed Handlers.
func (*Logger) RemoveFilter ¶
RemoveFilter removes an existed Filter.
func (*Logger) RemoveHandler ¶
RemoveHandler removes an existed Handler.
type SimpleConfig ¶ added in v0.4.0
type SimpleConfig struct { // Name is the name of Logger. It can be used later with GetLogger function. // Default to an empty name (the root logger). Name string // Use the specified encoding to format the output. Default to TextEncoding. Encoding encoding.Encoding // Specify that Logger will write the output to a file. Do NOT use together // with Writer. Filename string // Specify the mode to open file. Default to APPEND | CREATE | WRONLY. Filemode int // Specify the permission when creating the file. Default to 0666. Fileperm os.FileMode // The logging level. Default to WARNING. Level int // The time layout when format the time string. Default to RFC3339Nano. TimeLayout string // Specify that Logger will write the output to a file. Do NOT use together // with Filename. Writer io.Writer // contains filtered or unexported fields }
SimpleConfig supports to quickly create a Logger without configurating Emitter and Handler.
Example ¶
package main import ( "fmt" "os" "github.com/xybor-x/xylog" ) func main() { var config = &xylog.SimpleConfig{ Name: "simple-logger", Level: xylog.DEBUG, Writer: os.Stdout, } var logger, err = config.AddMacro("level", "levelname").Apply() if err != nil { fmt.Println("An error occurred:", err) } defer xylog.Flush() logger.Debug("logging message") logger.Event("create-user").Field("username", "foo"). Field("email", "bar@buzz.com").Field("Age", 25).Info() }
Output: level=DEBUG messsage="logging message" level=INFO event=create-user username=foo email=bar@buzz.com Age=25
func (*SimpleConfig) AddMacro ¶ added in v0.4.0
func (cfg *SimpleConfig) AddMacro(name, value string) *SimpleConfig
AddMacro adds a macro value to output format.
func (SimpleConfig) Apply ¶ added in v0.4.0
func (cfg SimpleConfig) Apply() (*Logger, error)
Apply creates a Logger based on the configuration.
type StreamEmitter ¶
type StreamEmitter struct {
// contains filtered or unexported fields
}
StreamEmitter writes logging message to a stream.
func NewBufferEmitter ¶ added in v0.4.1
func NewBufferEmitter(w io.Writer, bufsize int) *StreamEmitter
NewBufferEmitter creates a StreamEmitter which uses a Buffered Writer.
func NewStreamEmitter ¶
func NewStreamEmitter(w io.Writer) *StreamEmitter
NewStreamEmitter creates a StreamEmitter which writes logging message to a stream.
func (*StreamEmitter) Emit ¶
func (e *StreamEmitter) Emit(msg []byte)
Emit will be called after a record was decided to log.
func (*StreamEmitter) Flush ¶ added in v0.2.0
func (e *StreamEmitter) Flush()
Flush writes unflushed buffered data to destination.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package benchmarks is only used to benchmark the xylog.
|
Package benchmarks is only used to benchmark the xylog. |
Package encoding provides a fast encoding approach for xylog.
|
Package encoding provides a fast encoding approach for xylog. |
Package test provides utility test methods and objects for xylog unittest and benchmark.
|
Package test provides utility test methods and objects for xylog unittest and benchmark. |