Documentation ¶
Index ¶
- Variables
- func AddOutput(writers ...io.Writer)
- func Debug(v ...interface{})
- func Debugf(format string, args ...interface{})
- func Error(v ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(v ...interface{})
- func Fatalf(format string, args ...interface{})
- func GetLevelOutput(levelName string) io.Writer
- func Handle(handler Handler)
- func Hijack(hijacker func(ctx *pio.Ctx))
- func Info(v ...interface{})
- func Infof(format string, args ...interface{})
- func Install(logger ExternalLogger)
- func InstallStd(logger StdLogger)
- func Logf(level Level, format string, args ...interface{})
- func NewLine(newLineChar string)
- func Print(v ...interface{})
- func Println(v ...interface{})
- func Reset()
- func Scan(r io.Reader) (cancel func())
- func SetEnableTextColor()
- func SetLevel(levelName string)
- func SetOutput(w io.Writer)
- func Warn(v ...interface{})
- func Warnf(format string, args ...interface{})
- type ExternalLogger
- type Fields
- type Formatter
- type Frame
- type Handler
- type JSONFormatter
- type Level
- type LevelMetadata
- type Log
- type Logger
- func Child(key interface{}) *Logger
- func LastChild() *Logger
- func New() *Logger
- func RegisterFormatter(f Formatter) *Logger
- func SetChildPrefix(s string) *Logger
- func SetFormat(formatter string, opts ...interface{}) *Logger
- func SetLevelFormat(levelName string, formatter string, opts ...interface{}) *Logger
- func SetLevelOutput(levelName string, w io.Writer) *Logger
- func SetPrefix(s string) *Logger
- func SetStacktraceLimit(limit int) *Logger
- func SetTimeFormat(s string) *Logger
- func (l *Logger) AddOutput(writers ...io.Writer) *Logger
- func (l *Logger) Child(key interface{}) *Logger
- func (l *Logger) Clone() *Logger
- func (l *Logger) Debug(v ...interface{})
- func (l *Logger) Debugf(format string, args ...interface{})
- func (l *Logger) DisableNewLine() *Logger
- func (l *Logger) Error(v ...interface{})
- func (l *Logger) Errorf(format string, args ...interface{})
- func (l *Logger) Fatal(v ...interface{})
- func (l *Logger) Fatalf(format string, args ...interface{})
- func (l *Logger) GetLevelOutput(levelName string) io.Writer
- func (l *Logger) Handle(handler Handler)
- func (l *Logger) Hijack(hijacker func(ctx *pio.Ctx))
- func (l *Logger) Info(v ...interface{})
- func (l *Logger) Infof(format string, args ...interface{})
- func (l *Logger) Install(logger ExternalLogger)
- func (l *Logger) InstallStd(logger StdLogger)
- func (l *Logger) LastChild() *Logger
- func (l *Logger) Log(level Level, v ...interface{})
- func (l *Logger) Logf(level Level, format string, args ...interface{})
- func (l *Logger) Print(v ...interface{})
- func (l *Logger) Printf(format string, args ...interface{})
- func (l *Logger) Println(v ...interface{})
- func (l *Logger) RegisterFormatter(f Formatter) *Logger
- func (l *Logger) Scan(r io.Reader) (cancel func())
- func (l *Logger) SetChildPrefix(prefix string) *Logger
- func (l *Logger) SetEnableTextColor() *Logger
- func (l *Logger) SetFormat(formatter string, opts ...interface{}) *Logger
- func (l *Logger) SetLevel(levelName string) *Logger
- func (l *Logger) SetLevelFormat(levelName string, formatter string, opts ...interface{}) *Logger
- func (l *Logger) SetLevelOutput(levelName string, w io.Writer) *Logger
- func (l *Logger) SetOutput(w io.Writer) *Logger
- func (l *Logger) SetPrefix(s string) *Logger
- func (l *Logger) SetStacktraceLimit(limit int) *Logger
- func (l *Logger) SetTimeFormat(s string) *Logger
- func (l *Logger) Warn(v ...interface{})
- func (l *Logger) Warnf(format string, args ...interface{})
- func (l *Logger) Warningf(format string, args ...interface{})
- type StdLogger
Constants ¶
This section is empty.
Variables ¶
var ( // ErrorText can modify the prefix that will be prepended // to the output message log when `Error/Errorf` functions are being used. // // If "newColorfulText" is empty then it will update the text color version using // the default values by using the new raw text. // // Defaults to "[ERRO]" and pio.Red("[ERRO]"). // // Deprecated Use `Levels[ErrorLevel].SetText(string, string)` instead. ErrorText = Levels[ErrorLevel].SetText // WarnText can modify the prefix that will be prepended // to the output message log when `Warn/Warnf` functions are being used. // // If "newColorfulText" is empty then it will update the text color version using // the default values by using the new raw text. // // Defaults to "[WARN]" and pio.Purple("[WARN]"). // // Deprecated Use `Levels[WarnLevel].SetText(string, string)` instead. WarnText = Levels[WarnLevel].SetText // InfoText can modify the prefix that will be prepended // to the output message log when `Info/Infof` functions are being used. // // If "newColorfulText" is empty then it will update the text color version using // the default values by using the new raw text. // // Defaults to "[INFO]" and pio.LightGreen("[INFO]"). // // Deprecated Use `Levels[InfoLevel].SetText(string, string)` instead. InfoText = Levels[InfoLevel].SetText // DebugText can modify the prefix that will be prepended // to the output message log when `Info/Infof` functions are being used. // // If "newColorfulText" is empty then it will update the text color version using // the default values by using the new raw text. // // Defaults to "[DBUG]" and pio.Yellow("[DBUG]"). // // Deprecated Use `Levels[DebugLevel].SetText(string, string)` instead. DebugText = Levels[DebugLevel].SetText // GetTextForLevel is the function which // has the "final" responsibility to generate the text (colorful or not) // that is prepended to the leveled log message // when `Error/Errorf, Warn/Warnf, Info/Infof or Debug/Debugf` // functions are being called. // // It can be used to override the default behavior, at the start-up state. GetTextForLevel = func(level Level, enableColor bool) string { if meta, ok := Levels[level]; ok { return meta.Text(enableColor) } return "" } // GetNameForLevel is the function which // has the "final" responsibility to generagte the name of the level // that is prepended to the leveled log message GetNameForLevel = func(level Level) string { if meta, ok := Levels[level]; ok { return meta.Name } return "" } )
var Default = New()
Default is the package-level ready-to-use logger, level had set to "info", is changeable.
var Levels = map[Level]*LevelMetadata{ DisableLevel: { Name: "disable", AlternativeNames: []string{"disabled"}, Title: "", }, FatalLevel: { Name: "fatal", Title: "[FTAL]", ColorCode: pio.Red, Style: []pio.RichOption{pio.Background}, }, ErrorLevel: { Name: "error", Title: "[ERRO]", ColorCode: pio.Red, }, WarnLevel: { Name: "warn", AlternativeNames: []string{"warning"}, Title: "[WARN]", ColorCode: pio.Magenta, }, InfoLevel: { Name: "info", Title: "[INFO]", ColorCode: pio.Cyan, }, DebugLevel: { Name: "debug", Title: "[DBUG]", ColorCode: pio.Yellow, }, }
Levels contains the levels and their mapped (pointer of, in order to be able to be modified) metadata, callers are allowed to modify this package-level global variable without any loses.
var NopOutput = pio.NopOutput()
NopOutput disables the output.
var Now func() time.Time = time.Now
Now is called to set the log's timestamp value. It can be altered through initialization of the program to customize the behavior of getting the current time.
Functions ¶
func AddOutput ¶
AddOutput adds one or more `io.Writer` to the Default Logger's Printer.
If one of the "writers" is not a terminal-based (i.e File) then colors will be disabled for all outputs.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf will print when logger's Level is debug.
func Error ¶
func Error(v ...interface{})
Error will print only when logger's Level is error, warn, info or debug.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf will print only when logger's Level is error, warn, info or debug.
func Fatal ¶
func Fatal(v ...interface{})
Fatal `os.Exit(1)` exit no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf will `os.Exit(1)` no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.
func GetLevelOutput ¶
GetLevelOutput returns the responsible writer for the given "levelName". If not a registered writer is set for that level then it returns the logger's default printer. It does NOT return nil.
func Handle ¶
func Handle(handler Handler)
Handle adds a log handler to the default logger.
Handlers can be used to intercept the message between a log value and the actual print operation, it's called when one of the print functions called. If it's return value is true then it means that the specific handler handled the log by itself therefore no need to proceed with the default behavior of printing the log to the specified logger's output.
It stops on the handler which returns true firstly. The `Log` value holds the level of the print operation as well.
func Hijack ¶
Hijack adds a hijacker to the low-level logger's Printer. If you need to implement such as a low-level hijacker manually, then you have to make use of the pio library.
func Infof ¶
func Infof(format string, args ...interface{})
Infof will print when logger's Level is info or debug.
func Install ¶
func Install(logger ExternalLogger)
Install receives an external logger and automatically adapts its print functions.
Install adds a golog handler to support third-party integrations, it can be used only once per `golog#Logger` instance.
For example, if you want to print using a logrus logger you can do the following: `golog.Install(logrus.StandardLogger())`
Look `golog#Handle` for more.
func InstallStd ¶
func InstallStd(logger StdLogger)
InstallStd receives a standard logger and automatically adapts its print functions.
Install adds a golog handler to support third-party integrations, it can be used only once per `golog#Logger` instance.
Example Code:
import "log" myLogger := log.New(os.Stdout, "", 0) InstallStd(myLogger)
Look `golog#Handle` for more.
func Logf ¶
Logf prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.
func NewLine ¶
func NewLine(newLineChar string)
NewLine can override the default package-level line breaker, "\n". It should be called (in-sync) before the print or leveled functions.
See `github.com/kataras/pio#NewLine` and `Logger#NewLine` too.
func Println ¶
func Println(v ...interface{})
Println prints a log message without levels and colors. It adds a new line at the end.
func Scan ¶
Scan scans everything from "r" and prints its new contents to the logger's Printer's Output, forever or until the returning "cancel" is fired, once.
func SetEnableTextColor ¶
func SetEnableTextColor()
func SetLevel ¶
func SetLevel(levelName string)
SetLevel accepts a string representation of a `Level` and returns a `Level` value based on that "levelName".
Available level names are: "disable" "fatal" "error" "warn" "info" "debug"
Alternatively you can use the exported `Default.Level` field, i.e `Default.Level = golog.ErrorLevel`
Types ¶
type ExternalLogger ¶
type ExternalLogger interface { Print(...interface{}) Println(...interface{}) Error(...interface{}) Warn(...interface{}) Info(...interface{}) Debug(...interface{}) }
ExternalLogger is a typical logger interface. Any logger or printer that completes this interface can be used to intercept and handle the golog's messages.
See `Logger#Install` and `Logger#Handle` for more.
type Fields ¶
type Fields map[string]interface{}
Fields is a map type. One or more values of `Fields` type can be passed on all Log methods except `Print/Printf/Println` to set the `Log.Fields` field, which can be accessed through a custom LogHandler.
type Formatter ¶
type Formatter interface { // The name of the formatter. String() string // Set any options and return a clone, // generic. See `Logger.SetFormat`. Options(opts ...interface{}) Formatter // Writes the "log" to "dest" logger. Format(dest io.Writer, log *Log) bool }
Formatter is responsible to print a log to the logger's writer.
type Frame ¶
type Frame struct { // Function is the package path-qualified function name of // this call frame. If non-empty, this string uniquely // identifies a single function in the program. // This may be the empty string if not known. Function string `json:"function"` // Source contains the file name and line number of the // location in this frame. For non-leaf frames, this will be // the location of a call. Source string `json:"source"` }
Frame represents the log's caller.
func GetStacktrace ¶
GetStacktrace tries to return the callers of this function.
type Handler ¶
Handler is the signature type for logger's handler.
A Handler can be used to intercept the message between a log value and the actual print operation, it's called when one of the print functions called. If it's return value is true then it means that the specific handler handled the log by itself therefore no need to proceed with the default behavior of printing the log to the specified logger's output.
It stops on the handler which returns true firstly. The `Log` value holds the level of the print operation as well.
type JSONFormatter ¶
type JSONFormatter struct { Indent string // contains filtered or unexported fields }
JSONFormatter is a Formatter type for JSON logs.
func (*JSONFormatter) Format ¶
func (f *JSONFormatter) Format(dest io.Writer, log *Log) bool
Format prints the logs in JSON format.
Usage: logger.SetFormat("json") or logger.SetLevelFormat("info", "json")
func (*JSONFormatter) Options ¶
func (f *JSONFormatter) Options(opts ...interface{}) Formatter
Options sets the options for the JSON Formatter (currently only indent).
func (*JSONFormatter) String ¶
func (f *JSONFormatter) String() string
String returns the name of the Formatter. In this case it returns "json". It's used to map the formatter names with their implementations.
type Level ¶
type Level uint32
Level is a number which defines the log level.
const ( // DisableLevel will disable the printer. DisableLevel Level = iota // FatalLevel will `os.Exit(1)` no matter the level of the logger. // If the logger's level is fatal, error, warn, info or debug // then it will print the log message too. FatalLevel // ErrorLevel will print only errors. ErrorLevel // WarnLevel will print errors and warnings. WarnLevel // InfoLevel will print errors, warnings and infos. InfoLevel // DebugLevel will print on any level, fatals, errors, warnings, infos and debug logs. DebugLevel )
The available built'n log levels, users can add or modify a level via `Levels` field.
func ParseLevel ¶
ParseLevel returns a `golog.Level` from a string level. Note that all existing log levels (name, prefix and color) can be customized and new one can be added by the package-level `golog.Levels` map variable.
func (Level) MarshalJSON ¶
MarshalJSON implements the json marshaler for Level.
type LevelMetadata ¶
type LevelMetadata struct { // The Name of the Level // that named (lowercased) will be used // to convert a string level on `SetLevel` // to the correct Level type. Name string // AlternativeNames are the names that can be referred to this specific log level. // i.e Name = "warn" // AlternativeNames = []string{"warning"}, it's an optional field, // therefore we keep Name as a simple string and created this new field. AlternativeNames []string // Tha Title is the prefix of the log level. // See `ColorCode` and `Style` too. // Both `ColorCode` and `Style` should be respected across writers. Title string // ColorCode a color for the `Title`. ColorCode int // Style one or more rich options for the `Title`. Style []pio.RichOption }
LevelMetadata describes the information behind a log Level, each level has its own unique metadata.
func (*LevelMetadata) SetText ¶
func (m *LevelMetadata) SetText(title string, colorCode int, style ...pio.RichOption)
SetText can modify the prefix that will be prepended to the output message log when `Error/Errorf` functions are being used.
func (*LevelMetadata) Text ¶
func (m *LevelMetadata) Text(enableColor bool) string
Text returns the text that should be prepended to the log message when a specific log level is being written.
type Log ¶
type Log struct { // Logger is the original printer of this Log. Logger *Logger `json:"-"` // Time is the time of fired. Time time.Time `json:"-"` // Timestamp is the unix time in second of fired. Timestamp int64 `json:"timestamp,omitempty"` // Level is the log level. Level Level `json:"level"` // Message is the string reprensetation of the log's main body. Message string `json:"message"` // Fields any data information useful to represent this log. Fields Fields `json:"fields,omitempty"` // Stacktrace contains the stack callers when on `Debug` level. // The first one should be the Logger's direct caller function. Stacktrace []Frame `json:"stacktrace,omitempty"` // NewLine returns false if this Log // derives from a `Print` function, // otherwise true if derives from a `Println`, `Error`, `Errorf`, `Warn`, etc... // // This NewLine does not mean that `Message` ends with "\n" (or `pio#NewLine`). // NewLine has to do with the methods called, // not the original content of the `Message`. NewLine bool `json:"-"` }
A Log represents a log line.
type Logger ¶
type Logger struct { EnableTextColor bool Prefix string Level Level TimeFormat string // Limit stacktrace entries on `Debug` level. StacktraceLimit int // if new line should be added on all log functions, even the `F`s. // It defaults to true. // // See `golog#NewLine(newLineChar string)` as well. // // Note that this will not override the time and level prefix, // if you want to customize the log message please read the examples // or navigate to: https://github.com/menglh/golog/issues/3#issuecomment-355895870. NewLine bool Printer *pio.Printer // The per log level raw writers, optionally. LevelOutput map[Level]io.Writer LevelFormatter map[Level]Formatter // per level formatter. // contains filtered or unexported fields }
Logger is our golog.
func Child ¶
func Child(key interface{}) *Logger
Child (creates if not exists and) returns a new child Logger based on the current logger's fields.
Can be used to separate logs by category. If the "key" is string then it's used as prefix, which is appended to the current prefix one.
func New ¶
func New() *Logger
New returns a new golog with a default output to `os.Stdout` and level to `InfoLevel`.
func RegisterFormatter ¶
RegisterFormatter registers a Formatter for this logger.
func SetChildPrefix ¶
SetChildPrefix same as `SetPrefix` but it does NOT override the existing, instead the given "s" is appended to the current one. It's useful to chian loggers with their own names/prefixes. It does add the ": " in the end of "s" if it's missing. It returns itself.
func SetLevelFormat ¶
SetLevelFormat changes the output format for the given "levelName".
func SetLevelOutput ¶
SetLevelOutput sets a destination log output for the specific "levelName". For multiple writers use the `io.Multiwriter` wrapper.
func SetPrefix ¶
SetPrefix sets a prefix for the default package-level Logger.
The prefix is the first space-separated word that is being presented to the output. It's written even before the log level text.
Returns itself.
func SetStacktraceLimit ¶
SetStacktraceLimit sets a stacktrace entries limit on `Debug` level. Zero means all number of stack entries will be logged. Negative value disables the stacktrace field.
func SetTimeFormat ¶
SetTimeFormat sets time format for logs, if "s" is empty then time representation will be off.
func (*Logger) AddOutput ¶
AddOutput adds one or more `io.Writer` to the Logger's Printer.
If one of the "writers" is not a terminal-based (i.e File) then colors will be disabled for all outputs.
Returns itself.
func (*Logger) Child ¶
Child (creates if not exists and) returns a new child Logger based on the current logger's fields.
Can be used to separate logs by category. If the "key" is string then it's used as prefix, which is appended to the current prefix one.
func (*Logger) Clone ¶
Clone returns a copy of this "l" Logger. This copy is returned as pointer as well.
func (*Logger) Debug ¶
func (l *Logger) Debug(v ...interface{})
Debug will print when logger's Level is debug.
func (*Logger) DisableNewLine ¶
DisableNewLine disables the new line suffix on every log function, even the `F`'s, the caller should add "\n" to the log message manually after this call.
Returns itself.
func (*Logger) Error ¶
func (l *Logger) Error(v ...interface{})
Error will print only when logger's Level is error, warn, info or debug.
func (*Logger) Fatal ¶
func (l *Logger) Fatal(v ...interface{})
Fatal `os.Exit(1)` exit no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.
func (*Logger) Fatalf ¶
Fatalf will `os.Exit(1)` no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.
func (*Logger) GetLevelOutput ¶
GetLevelOutput returns the responsible writer for the given "levelName". If not a registered writer is set for that level then it returns the logger's default printer. It does NOT return nil.
func (*Logger) Handle ¶
Handle adds a log handler.
Handlers can be used to intercept the message between a log value and the actual print operation, it's called when one of the print functions called. If it's return value is true then it means that the specific handler handled the log by itself therefore no need to proceed with the default behavior of printing the log to the specified logger's output.
It stops on the handler which returns true firstly. The `Log` value holds the level of the print operation as well.
func (*Logger) Hijack ¶
Hijack adds a hijacker to the low-level logger's Printer. If you need to implement such as a low-level hijacker manually, then you have to make use of the pio library.
func (*Logger) Info ¶
func (l *Logger) Info(v ...interface{})
Info will print when logger's Level is info or debug.
func (*Logger) Install ¶
func (l *Logger) Install(logger ExternalLogger)
Install receives an external logger and automatically adapts its print functions.
Install adds a golog handler to support third-party integrations, it can be used only once per `golog#Logger` instance.
For example, if you want to print using a logrus logger you can do the following: `Install(logrus.StandardLogger())`
Look `golog#Logger.Handle` for more.
func (*Logger) InstallStd ¶
InstallStd receives a standard logger and automatically adapts its print functions.
Install adds a golog handler to support third-party integrations, it can be used only once per `golog#Logger` instance.
Example Code:
import "log" myLogger := log.New(os.Stdout, "", 0) InstallStd(myLogger)
Look `golog#Logger.Handle` for more.
func (*Logger) Log ¶
Log prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.
func (*Logger) Logf ¶
Logf prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.
func (*Logger) Print ¶
func (l *Logger) Print(v ...interface{})
Print prints a log message without levels and colors.
func (*Logger) Printf ¶
Printf formats according to a format specifier and writes to `Printer#Output` without levels and colors.
func (*Logger) Println ¶
func (l *Logger) Println(v ...interface{})
Println prints a log message without levels and colors. It adds a new line at the end, it overrides the `NewLine` option.
func (*Logger) RegisterFormatter ¶
RegisterFormatter registers a Formatter for this logger.
func (*Logger) Scan ¶
Scan scans everything from "r" and prints its new contents to the logger's Printer's Output, forever or until the returning "cancel" is fired, once.
func (*Logger) SetChildPrefix ¶
SetChildPrefix same as `SetPrefix` but it does NOT override the existing, instead the given "prefix" is appended to the current one. It's useful to chian loggers with their own names/prefixes. It does add the ": " in the end of "prefix" if it's missing. It returns itself.
func (*Logger) SetEnableTextColor ¶
func (*Logger) SetLevel ¶
SetLevel accepts a string representation of a `Level` and returns a `Level` value based on that "levelName".
Available level names are: "disable" "fatal" "error" "warn" "info" "debug"
Alternatively you can use the exported `Level` field, i.e `Level = golog.ErrorLevel`
Returns itself.
func (*Logger) SetLevelFormat ¶
SetLevelFormat changes the output format for the given "levelName".
func (*Logger) SetLevelOutput ¶
SetLevelOutput sets a destination log output for the specific "levelName". For multiple writers use the `io.Multiwriter` wrapper.
func (*Logger) SetOutput ¶
SetOutput overrides the Logger's Printer's Output with another `io.Writer`.
Returns itself.
func (*Logger) SetPrefix ¶
SetPrefix sets a prefix for this "l" Logger.
The prefix is the text that is being presented to the output right before the log's message.
Returns itself.
func (*Logger) SetStacktraceLimit ¶
SetStacktraceLimit sets a stacktrace entries limit on `Debug` level. Zero means all number of stack entries will be logged. Negative value disables the stacktrace field.
func (*Logger) SetTimeFormat ¶
SetTimeFormat sets time format for logs, if "s" is empty then time representation will be off.
Returns itself.
func (*Logger) Warn ¶
func (l *Logger) Warn(v ...interface{})
Warn will print when logger's Level is warn, info or debug.
func (*Logger) Warningf ¶
Warningf exactly the same as `Warnf`. It's here for badger integration: https://github.com/dgraph-io/badger/blob/ef28ef36b5923f12ffe3a1702bdfa6b479db6637/logger.go#L25
type StdLogger ¶
type StdLogger interface { Printf(format string, v ...interface{}) Print(v ...interface{}) Println(v ...interface{}) }
StdLogger is the standard log.Logger interface. Any logger or printer that completes this interface can be used to intercept and handle the golog's messages.
See `Logger#Install` and `Logger#Handle` for more.
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
level-output
Package main shows how you can register a log output per level.
|
Package main shows how you can register a log output per level. |