Categorygithub.com/zoumo/logdog
modulepackage
0.0.0-20170807090711-f8d72e099cbf
Repository: https://github.com/zoumo/logdog.git
Documentation: pkg.go.dev

# README

Logdog

Why logdog

Log is the most loyal friend for programmers -- Jim Zhang

Logdog is a Go logging package for Humans™ inspired by Python’s logging module.

Overview

terminal.png

Getting Started

package main

import (
	"github.com/zoumo/logdog"
)

func init() {
	// set min level, only log info or above can be emitted
	logdog.SetLevel(logdog.INFO)

	// enable logger get caller func's filename and lineno
	logdog.EnableRuntimeCaller(true)
}

func main() {
	logdog.Debug("this is debug")
	// Fields should be the last arg
	logdog.Info("this is info", logdog.Fields{"x": "test"})
}

Introduce

Logging Flow

logging flow

Logger Mindmap

logger mindmap

Fields

Inspired by Logrus. the Fields must be the LAST arg in log fucntion.

	logdog.Info("this is info, msg ", "some msg", logdog.Fields{"x": "test"})
	logdog.Infof("this is info, msg %s", "some msg", logdog.Fields{"x": "test"})

Loggers

Logger have a threefold job. First, they expose several methods to application code so that applications can log messages at runtime. Second, logger objects determine which log messages to act upon based upon severity (the default filtering facility) or filter objects. Third, logger objects pass along relevant log messages to all interested log handlers.

I do not adopt the inheritance features in Python logging, because it is obscure, intricate and useless. I would like the Logger be simple and readable

Handlers

Handler is responsible for dispatching the appropriate log messages to the handler’s specified destination. Logger can add zero or more handlers to themselves with AddHandler() method. For example to send all log messages to stdout , all log messages of error or higher level to a log file

import (
    "github.com/zoumo/logdog"
)

func main() {
    logdog.DisableExistingLoggers()
    handler := logdog.NewStreamHandler()
    handler2 := logdog.NewFileHandler()
    handler2.LoadConfig(logdog.Config{
        "level"   : "ERROR",
		"filename": "./test",
	})
    logdog.AddHandler(handler)
    
    logdog.Debug("this is debug")
    logdog.Error("this is error")
}

Handler is a Interface Type.

type Handler interface {
    // Handle the specified record, filter and emit
    Handle(*LogRecord)
    // Check if handler should filter the specified record
    Filter(*LogRecord) bool
    // Emit log record to output - e.g. stderr or file
    Emit(*LogRecord)
    // Close output stream, if not return error
    Close() error
}

Logdog comes with built-in handlers: NullHandler, SteamHandler, FileHandler. Maybe provide more extra handlers in the future, e.g. RotatingFileHandler

Formatters

Formatters configure the final order, structure, and contents of the log message Each Handler contains one Formatter, because only Handler itself knows which Formatter should be selected to determine the order, structure, and contents of log message Logdog comes with built-in formatters: TextFormatter, JsonFormatter Formatter is a Interface Type

type Formatter interface {
	Format(*LogRecord) (string, error)
}

TextFormatter

the default TextFormatter takes three args:

argdescriptiondefault
DateFmtdate time format string"%Y-%m-%d %H:%M:%S"
Fmtlog message format string%(color)[%(time)] [%(levelname)] [%(filename):%(lineno)]%(end_color) %(message)
EnableColorsenable print log with color or nottrue

The DateFmt format string looks like python datetime format string the possible keys are documented in go-when Strftime

The Fmt message format string uses %(<dictionary key>) styled string substitution; the possible keys :

key namedescription
nameName of the logger (logging channel)
levelnoNumeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL)
levelnameText logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
pathnameFull pathname of the source file where the logging call was issued (if available) or maybe ??
filenameFilename portion of pathname
linenoSource line number where the logging call was issued (if available)
funcnameFunction name of caller or maybe ??
timeTextual time when the LogRecord was created
messageThe result of record.getMessage(), computed just as the record is emitted
colorprint color
end_colorreset color

Configuring Logging

Programmers can configure logging in two ways:

  1. Creating loggers, handlers, and formatters explicitly using Golang code that calls the configuration methods listed above.
  2. Creating a json format config string and passing it to the LoadJSONConfig() function.
package main

import (
	"github.com/zoumo/logdog"
)

func main() {
    
    logger := logdog.GetLogger("test")
    
    handler := logdog.NewStreamHandler()
    handler2 := logdog.NewFileHandler()
    handler2.LoadConfig(logdog.Config{
		"filename": "./test",
    })
    
    logger.AddHandler(handler, handler2)
    
    logger.SetLevel(logdog.INFO)
    logger.EnableRuntimeCaller(true)
    
	logger.Debug("this is debug")
	logger.Info("this is info", logdog.Fields{"x": "test"})
}
package main

import (
	"github.com/zoumo/logdog"
)

func main() {

	config := []byte(`{
        "disable_existing_loggers": true,
        "handlers": {
            "null": {
                "class": "NullHandler",
                "level": "DEBUG"
            },
            "console": {
                "class": "StreamHandler",
                "formatter": "default",
                "level": "INFO"
            }
        },
        "loggers": {
            "app": {
                "level": "DEBUG",
                "enable_runtime_caller": true,
                "handlers": ["null", "console"]
            }
        }

    }`)

    logdog.LoadJSONConfig(config)
    logger := logdog.GetLogger("app")
    
	logger.Debug("this is debug")
	logger.Info("this is info", logdog.Fields{"x": "test"})
}

Requirement

TODO

  • rotating file handler
  • use goroutine to accelerate logdog
  • more handler
  • godoc

Thanks

# Packages

Copyright 2016 Jim Zhang ([email protected]) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
No description provided by the author

# Functions

AddHandlers is an alias of root.AddHandler.
ApplyOptions is an alias of root.ApplyOptions.
Debug is an alias of root.Debug.
Debugf is an alias of root.Debugf.
DisableExistingLoggers closes all existing loggers and unregister them.
Error is an alias of root.Error.
Errorf is an alias of root.Errorf.
Fatal is an alias of root.Critical.
Fatalf is an alias of root.Criticalf.
Flush ...
FormatTime returns the creation time of the specified LogRecord as formatted text.
GetConstructor returns an Constructor registered with the given name if not, returns nil.
GetFormatter returns an Formatter registered with the given name.
GetHandler returns a Handler registered with the given name.
GetLevel returns a Level registered with the given name.
GetLogger returns an logger by name if not, create one and add it to logger register.
Info is an alias of root.Info.
Infof is an alias of root.Infof.
IsColorTerminal return isTerminal and isColorTerminal.
LoadJSONConfig loads a json config if DisableExistingLoggers is true, all existing loggers will be closed, then a new root logger will be created.
NewFileHandler returns a new FileHandler fully initialized.
NewJSONFormatter returns a JSONFormatter with default config.
NewLogger returns a new Logger.
NewLogRecord returns a new log record.
NewNullHandler returns a NullHandler.
NewStreamHandler returns a new StreamHandler fully initialized.
NewTextFormatter return a new TextFormatter with default config.
Notice is an alias of root.Notice.
Noticef is an alias of root.Noticef.
OptionCallerStackDepth is an option.
OptionDiscardOutput is an option used in every target which has fields named `Output` and make all Read | Write | Close calls succeed without doing anything.
OptionEnableRuntimeCaller is an option useed in : used in every target which has fields named `EnableRuntimeCaller`.
OptionHandlers is an option used in every target which has fields named `Handlers`.
OptionName is an option used in every target which has fields named `Name`.
OptionOutput is an option used in every target which has fields named `Output`.
Panic an alias of root.Panic.
Panicf is an alias of root.Panicf.
RegisterConstructor binds name and Constructor.
RegisterFormatter binds name and Formatter.
RegisterHandler binds name and Handler.
RegisterLevel binds name and level.
Warn is an alias of root.Warn.
Warnf is an alias of root.Warnf.
Warning is an alias of root.Warning.
Warningf is an alias of root.Warningf.

# Constants

0x11111111.
0x00000001.
DefaultCallerStackDepth is 2 because you should ascend 2 frames to get true caller function by default.
DefaultDateFmtTemplate is the default log time string format value for TextFormatter.
DefaultFmtTemplate is the default log string format value for TextFormatter.
0x00001000.
0x00100000.
0x00000010.
NothingLevel log level only used in filter.
0x00010000.
RootLoggerName is the name of root logger.
0x00000100.
0x00000100.

# Variables

ColorHash describes colors of different log level you can add new color for your own log level.
DefaultFormatter is the default formatter of TextFormatter without color.
Discard is an io.ReadWriteCloser on which all Read | Write | Close calls succeed without doing anything.
ForceColor forces formatter use color output.
LogRecordFieldRegexp is the field regexp for example, I will replace %(name) of real record name TODO support %[(name)][flags][width].[precision]typecode.
TerminalFormatter is an TextFormatter with color.

# Structs

FileHandler is a handler similar to SteamHandler if specified file and it will close the file.
JSONFormatter can convert LogRecord to json text.
LogConfig defines the configuration of logger.
Logger entries pass through the formatter before logged to Output.
LogRecord defines a real log record should be.
NullHandler is an example handler doing nothing.
StreamHandler is a handler which writes logging records, appropriately formatted, to a stream.
TextFormatter is the default formatter used to convert a LogRecord to text.

# Interfaces

ConfigLoader is an interface which con load map[string]interface{} config.
Formatter is an interface which can convert a LogRecord to string.
Handler specifies how to write a LoadConfig, appropriately formatted, to output.
Option is an interface which is used to set options for the target.

# Type aliases

Config is a alias of map[string]interface{}.
Constructor is a function which returns an ConfigLoader.
Fields is an alias to man[string]interface{}.
Level is a logging priority.