l3

package
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

README

go-l3

A Lightweight Levelled Logger for Go

Features

  • Multiple logging levels OFF,ERROR,INFO,DEBUG,TRACE
  • Console and File based writers
  • Rolling file support ([WIP]
  • Ability to specify log levels for a specific package
  • Internationalisation (i18n) support ([WIP])
  • Async logging support
  • Configuration can be done using either a file,env variables,Struct values at runtime.

Usage

Simple Usage

The simplest example is as shown below.

    import (
	"errors"
	
	"go.nandlabs.io/commons/l3"
)

//logger Package Level Logger
var logger l3.Logger = l3.Get()

func main() {
	logger.Info("This is an info log msg")
	logger.Warn("This is an warning msg")
	logger.Error("This is an error log msg")
	logger.Error("This is an error log msg with optional error", errors.New("Some error happened here "))
	logger.Warn("Message with any level can also have an error", errors.New("Some error happened here but want it as info"))

}

    

This will create a logger with default configuration

  • Logs get written to console
  • Log levels ERROR, WARN get written to stderr and remaining levels to stdout
  • The default log level is INFO this can be overwritten using an env variable or log config file. See Log [Configuration](#Log Configuration) section for more details.

Log Configuration

The below table specifies the configuration parameters for logging The log can be configured in the following ways.

1. File Based Configuration

The file based configuration allows a file with log configuration to be specified. Here is a sample file configuration based on json.

{
     "format": "json",
     "async": false,
     "defaultLvl": "INFO",
     "includeFunction": true,
     "includeLineNum": true,
     "pkgConfigs": [
       {
         "pkgName": "main",
         "level": "INFO"
       }
     ],
     "writers": [
       {
         "console": {
           "errToStdOut": false,
           "warnToStdOut": false
         }
       }
       {
         "file": {
           "defaultPath": "/tmp/default.log"
         }
       },
       
     ]
   }

following table specifies the field values

Field Name Type Description Default Value
format String The output format of the log message. The valid values are text or json text
async Boolean Determines if the message is to be written to the destination asynchronously. If set to true then the LogMessage is prepared synchronously.However, it is written to destination in a async fashion. false
defaultLvl String Sets the default Logging level for the Logger. This is a global value. For overriding the log levels for a specific packages use pkgConfigs. The valid values are OFF,ERROR,INFO,DEBUG,TRACE INFO
datePattern String The timestamp format for the log entries.Valid values are the ones acceptable bytime.Format(<pattern>) function. As defined by time.RFC3339
includeFunction Boolean Determines if the Function Name needs to be printed in logs. false
includeLineNum Boolean Determines if the line number needs to be printed in logs. This config takes into effect only if includeFunction=true false
pkgConfigs Array This field consists array of package specific configuration.
{"pkgName": "<packageName>","level": "<Level>"}
null
writers Array Array of writers either file or console based writer. Console Writer Has the following has the following configuration {"console": {"errToStdOut": false,"warnToStdOut": false}}.Log levels except ERROR and WARN are written to os.Stdout. The Entries for the ERROR,WARN can be written to either os.StdErr or os.Stdout
For a file based log destination,paths for each level can be specified as follows.
{"file": { "defaultPath": "<file Path>","errorPath": "<file Path>","warnPath": "<file Path>","infoPath": "<file Path>","debugPath": "<file Path>","tracePath": "<file Path>" }
If any of the errorPath,warnPath,infoPath,debugPath,tracePath is not specified then default path for that level is applied. If all of the level specific paths are specified then the defaultPath value is ignored.
N/A

By Default the logging framework looks for a file named log-config.json in the same directory if the application. This is the default location.This location can be overridden using an environment variable GC_LOG_CONFIG_FILE. If the framework cannot resolve the configuration file either in the default location or at the location specified by environment variable, then the framework loads a default configuration as described below.

2. Default Log Config- With ENV variables override

The default log configuration will write the log entries to the console and the framework default log level is INFO. Few fields can be overwritten using environment variables. The following table shows those env variables

Environment Var Converted Type Description Default Value
GC_LOG_ASYNC Boolean Determines if the message is to be written to the destination asynchronously. If set to true then the LogMessage is prepared synchronously.However, it is written to destination in a async fashion. false
GC_LOG_FMT String The output format of the log message. The valid values are text or json text
GC_LOG_DEF_LEVEL String Sets the default Logging level for the Logger. This is a global value. For overriding the log levels for a specific packages use pkgConfigs. The valid values are OFF,ERROR,INFO,DEBUG,TRACE INFO
GC_LOG_TIME_FMT String The timestamp format for the log entries.Valid values are the ones acceptable bytime.Format(<pattern>) function. As defined by time.RFC3339
GC_LOG_WARN_STDOUT Boolean Indicates whether the log entries with WARN level needs to be written to os.Stdout instead of os.Stderr false
GC_LOG_ERR_STDOUT Boolean Indicates whether the log entries with ERROR level needs to be written to os.Stdout instead of os.Stderr false
3. Configuring logging during runtime.

The log configuration can be set at runtime using the l3.Configure(l *LogConfig). This is a global level log configuration and will impact all instances of logger

Documentation

Index

Constants

View Source
const (
	// LogConfigEnvProperty specifies the environment variable that would specify the file location
	LogConfigEnvProperty = "GC_LOG_CONFIG_FILE"
	//DefaultlogFilePath specifies the location where the application should search for log config if the LogConfigEnvProperty is not specified
	DefaultlogFilePath = "./log-config.json"
)

Variables

View Source
var Levels = [...]string{
	"OFF",
	"ERROR",
	"WARN",
	"INFO",
	"DEBUG",
	"TRACE",
}

Levels of the logging by severity

View Source
var LevelsBytes = [...][]byte{
	[]byte("OFF"),
	[]byte("ERROR"),
	[]byte("WARN"),
	[]byte("INFO"),
	[]byte("DEBUG"),
	[]byte("TRACE"),
}

LevelsBytes of the logging by Level

View Source
var LevelsMap = map[string]Level{
	"OFF":   Off,
	"ERROR": Err,
	"WARN":  Warn,
	"INFO":  Info,
	"DEBUG": Debug,
	"TRACE": Trace,
}

LevelsMap of the logging by Level string Level type

Functions

func Configure

func Configure(l *LogConfig)

Configure Logging

Types

type BaseLogger

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

BaseLogger struct.

func (*BaseLogger) Debug

func (l *BaseLogger) Debug(a ...interface{})

Debug BaseLogger

func (*BaseLogger) DebugF

func (l *BaseLogger) DebugF(f string, a ...interface{})

DebugF BaseLogger

func (*BaseLogger) Error

func (l *BaseLogger) Error(a ...interface{})

Error BaseLogger

func (*BaseLogger) ErrorF

func (l *BaseLogger) ErrorF(f string, a ...interface{})

ErrorF BaseLogger with formatting of the messages

func (*BaseLogger) Info

func (l *BaseLogger) Info(a ...interface{})

Info BaseLogger

func (*BaseLogger) InfoF

func (l *BaseLogger) InfoF(f string, a ...interface{})

InfoF BaseLogger

func (*BaseLogger) IsEnabled

func (l *BaseLogger) IsEnabled(sev Level) bool

IsEnabled function returns if the current

func (*BaseLogger) Trace

func (l *BaseLogger) Trace(a ...interface{})

Trace BaseLogger

func (*BaseLogger) TraceF

func (l *BaseLogger) TraceF(f string, a ...interface{})

TraceF BaseLogger

func (*BaseLogger) Warn

func (l *BaseLogger) Warn(a ...interface{})

Warn BaseLogger

func (*BaseLogger) WarnF

func (l *BaseLogger) WarnF(f string, a ...interface{})

WarnF BaseLogger with formatting of the messages

type ConsoleConfig

type ConsoleConfig struct {
	//WriteErrToStdOut write error messages to os.Stdout .
	WriteErrToStdOut bool `json:"errToStdOut" yaml:"errToStdOut"`
	//WriteWarnToStdOut write warn messages to os.Stdout .
	WriteWarnToStdOut bool `json:"warnToStdOut" yaml:"warnToStdOut"`
}

ConsoleConfig - Configuration of console based logging. All Log Levels except ERROR and WARN are written to os.Stdout The ERROR and WARN log levels can be written to os.Stdout or os.Stderr, By default they go to os.Stderr

type ConsoleWriter

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

ConsoleWriter struct

func (*ConsoleWriter) Close

func (cw *ConsoleWriter) Close() error

Close close ConsoleWriter

func (*ConsoleWriter) DoLog

func (cw *ConsoleWriter) DoLog(logMsg *LogMessage)

DoLog consoleWriter

func (*ConsoleWriter) InitConfig

func (cw *ConsoleWriter) InitConfig(w *WriterConfig)

InitConfig ConsoleWriter

type FileConfig

type FileConfig struct {
	//FilePath for the file based log writer
	DefaultPath string `json:"defaultPath" yaml:"defaultPath"`
	ErrorPath   string `json:"errorPath" yaml:"errorPath"`
	WarnPath    string `json:"warnPath" yaml:"warnPath"`
	InfoPath    string `json:"infoPath" yaml:"infoPath"`
	DebugPath   string `json:"debugPath" yaml:"debugPath"`
	TracePath   string `json:"tracePath" yaml:"tracePath"`
	//RollType must indicate one for the following(case sensitive). SIZE,DAILY
	RollType string `json:"rollType" yaml:"rollType"`
	//Max Size of the of the file. Only takes into effect when the RollType="SIZE"
	MaxSize int64 `json:"maxSize" yaml:"maxSize"`
	//CompressOldFile is taken into effect if file rolling is enabled by setting a RollType.
	//Default implementation will just do a GZIP of the file leaving the file with <file_name>.gz
	CompressOldFile bool `json:"compressOldFile" yaml:"compressOldFile"`
}

FileConfig - Configuration of file based logging

type FileWriter

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

FileWriter struct

func (*FileWriter) Close

func (fw *FileWriter) Close() error

Close stream

func (*FileWriter) DoLog

func (fw *FileWriter) DoLog(logMsg *LogMessage)

DoLog FileWriter

func (*FileWriter) InitConfig

func (fw *FileWriter) InitConfig(w *WriterConfig)

InitConfig FileWriter

type Level

type Level int

Level specifies the log level

const (
	//Off - No logging
	Off Level = iota
	//Err - logging only for error level.
	Err
	//Warn - logging turned on for warning & error levels
	Warn
	//Info - logging turned on for Info, Warning and Error levels.
	Info
	//Debug - Logging turned on for Debug, Info, Warning and Error levels.
	Debug
	//Trace - Logging turned on for Trace,Info, Warning and error Levels.
	Trace
)

func (Level) String

func (sev Level) String() (string, error)

String method to get the Severity String

type LogConfig

type LogConfig struct {

	//Format of the log. valid values are text,json
	//Default is text
	Format string `json:"format,omitempty" yaml:"format,omitempty"`
	//Async Flag to indicate if the writing of the flag is asynchronous.
	//Default value is false
	Async bool `json:"async,omitempty" yaml:"async,omitempty"`
	//QueueSize to indicate the number log routines that can be queued  to use in background
	//This value is used only if the async value is set to true.
	//Default value for the number items to be in queue 512
	QueueSize int `json:"queue_size,omitempty" yaml:"queueSize,omitempty"`
	//Date - Defaults to  time.RFC3339 pattern
	DatePattern string `json:"datePattern,omitempty" yaml:"datePattern,omitempty"`
	//IncludeFunction will include the calling function name  in the log entries
	//Default value : false
	IncludeFunction bool `json:"includeFunction,omitempty" yaml:"includeFunction,omitempty"`
	//IncludeLineNum ,includes Line number for the log file
	//If IncludeFunction Line is set to false this config is ignored
	IncludeLineNum bool `json:"includeLineNum,omitempty" yaml:"includeLineNum,omitempty"`
	//DefaultLvl that will be used as default
	DefaultLvl string `json:"defaultLvl" yaml:"defaultLvl"`
	//PackageConfig that can be used to
	PkgConfigs []*PackageConfig `json:"pkgConfigs" yaml:"pkgConfigs"`
	//Writers writers for the logger. Need one for all levels
	//If a writer is not found for a specific level it will fallback to os.Stdout if the level is greater then Warn and os.Stderr otherwise
	Writers []*WriterConfig `json:"writers" yaml:"writers"`
}

LogConfig - Configuration & Settings for the logger.

type LogMessage

type LogMessage struct {
	Time    time.Time     `json:"timestamp"`
	FnName  string        `json:"function,omitempty"`
	Line    int           `json:"line,omitempty"`
	Content *bytes.Buffer `json:"msg"`
	Level   Level         `json:"level"`
	Buf     *bytes.Buffer
}

LogMessage struct.

type LogWriter

type LogWriter interface {
	InitConfig(w *WriterConfig)
	DoLog(logMsg *LogMessage)
	io.Closer
}

LogWriter interface

type Logger

type Logger interface {
	Error(a ...interface{})
	ErrorF(f string, a ...interface{})
	Warn(a ...interface{})
	WarnF(f string, a ...interface{})
	Info(a ...interface{})
	InfoF(f string, a ...interface{})
	Debug(a ...interface{})
	DebugF(f string, a ...interface{})
	Trace(a ...interface{})
	TraceF(f string, a ...interface{})
}

func Get

func Get() Logger

Get function will return the logger object for that package

type PackageConfig

type PackageConfig struct {
	//PackageName
	PackageName string `json:"pkgName" yaml:"pkgName"`
	//Level to be set valid values : OFF,ERROR,WARN,INFO,DEBUG,TRACE
	Level string `json:"level" yaml:"level"`
}

PackageConfig configuration

type WriterConfig

type WriterConfig struct {
	//File reference. Non mandatory but one of file or console logger is required.
	File *FileConfig `json:"file,omitempty" yaml:"file,omitempty"`
	//Console reference
	Console *ConsoleConfig `json:"console,omitempty" yaml:"console,omitempty"`
}

WriterConfig struct

Jump to

Keyboard shortcuts

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