Documentation ΒΆ
Overview ΒΆ
CBSD 3-Clause License
Copyright (c) 2017-2022, Gerasimos (Makis) Maropoulos (kataras2006@hotmail.com) All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* Package golog provides an easy to use foundation for your logging operations.
Source code and other details for the project are available at GitHub:
https://github.com/kataras/golog
Current Version ΒΆ
0.1.12
Installation ΒΆ
The only requirement is the Go Programming Language
$ go get github.com/kataras/golog@latest
Overview ΒΆ
Example code:
package main import ( "github.com/kataras/golog" ) func main() { // Default Output is `os.Stdout`, // but you can change it: // golog.SetOutput(os.Stderr) // Time Format defaults to: "2006/01/02 15:04" // you can change it to something else or disable it with: golog.SetTimeFormat("") // Level defaults to "info", // but you can change it: golog.SetLevel("debug") golog.Println("This is a raw message, no levels, no colors.") golog.Info("This is an info message, with colors (if the output is terminal)") golog.Warn("This is a warning message") golog.Error("This is an error message") golog.Debug("This is a debug message") }
New ΒΆ
Golog has a default, package-level initialized instance for you, however you can choose to create and use a logger instance for a specific part of your application.
Example Code:
package main import ( "github.com/kataras/golog" ) func main() { log := golog.New() // Default Output is `os.Stdout`, // but you can change it: // log.SetOutput(os.Stderr) // Level defaults to "info", // but you can change it: log.SetLevel("debug") log.Println("This is a raw message, no levels, no colors.") log.Info("This is an info message, with colors (if the output is terminal)") log.Warn("This is a warning message") log.Error("This is an error message") log.Debug("This is a debug message") }
Format ΒΆ
Golog sets colors to levels when its `Printer.Output` is actual a compatible terminal which can renders colors, otherwise it will downgrade itself to a white foreground.
Golog has functions to print a formatted log too.
Example Code:
golog.Infof("[%d] This is an info %s", 1, "formatted log") golog.Warnf("[%d] This is an info %s", 1, "formatted log") golog.Errorf("[%d] This is an info %s", 1, "formatted log") golog.Debugf("[%d] This is an info %s", 1, "formatted log")
Output ΒΆ
Golog takes a simple `io.Writer` as its underline Printer's Output.
Example Code:
golog.SetOutput(io.Writer)
You can even override the default line braker, "\n", by using the `golog#NewLine` function at startup.
Example Code:
golog.NewLine("\r\n")
Levels ΒΆ
Golog is a leveled logger, therefore you can set a level and print whenever the print level is valid with the set-ed one.
Available built'n levels are:
// DisableLevel will disable printer DisableLevel Level = iota // 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, errors, warnings, infos and debug messages DebugLevel
Below you'll learn a way to add a custom level or modify an existing level.
The default colorful text(or raw text for unsupported outputs) for levels can be overridden by using the `golog#ErrorText, golog#WarnText, golog#InfoText and golog#DebugText` functions.
Example Code:
package main import ( "github.com/kataras/golog" ) func main() { // First argument is the raw text for outputs // second argument is the color code // and the last, variadic argument can be any `kataras/pio.RichOption`, e.g. pio.Background, pio.Underline. // Default is "[ERRO]" golog.ErrorText("|ERROR|", 31) // Default is "[WARN]" golog.WarnText("|WARN|", 32) // Default is "[INFO]" golog.InfoText("|INFO|", 34) // Default is "[DBUG]" golog.DebugText("|DEBUG|", 33) // Business as usual... golog.SetLevel("debug") golog.Println("This is a raw message, no levels, no colors.") golog.Info("This is an info message, with colors (if the output is terminal)") golog.Warn("This is a warning message") golog.Error("This is an error message") golog.Debug("This is a debug message") }
Golog gives you the power to add or modify existing levels is via Level Metadata.
Example Code:
package main import ( "github.com/kataras/golog" ) func main() { // Let's add a custom level, // // It should be starting from level index 6, // because we have 6 built'n levels (0 is the start index): // disable, // fatal, // error, // warn, // info // debug // First we create our level to a golog.Level // in order to be used in the Log functions. var SuccessLevel golog.Level = 6 // Register our level, just three fields. golog.Levels[SuccessLevel] = &golog.LevelMetadata{ Name: "success", Title: "[SUCC]", ColorCode: 32, // Green } // create a new golog logger myLogger := golog.New() // set its level to the higher in order to see it // ("success" is the name we gave to our level) myLogger.SetLevel("success") // and finally print a log message with our custom level myLogger.Logf(SuccessLevel, "This is a success log message with green color") }
The logger's level can be changed via passing one of the level constants to the `Level` field or by passing its string representation to the `SetLevel` function.
Example Code:
golog.SetLevel("disable") golog.SetLevel("fatal") golog.SetLevel("error") golog.SetLevel("warn") golog.SetLevel("info") golog.SetLevel("debug")
Integrations ΒΆ
Transaction with your favorite, but deprecated logger is easy. Golog offers two basic interfaces, the `ExternalLogger` and the `StdLogger` that can be directly used as arguments to the `Install` function in order to adapt an external logger.
Outline:
// 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()) // // Or the standard log's Logger: // // import "log" // myLogger := log.New(os.Stdout, "", 0) // Install(myLogger) // // Or even the slog/log's Logger: // // import "log/slog" // myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // Install(myLogger) OR Install(slog.Default()) // // Look `golog#Logger.Handle` for more. Install(logger ExternalLogger)
Logrus Integration ΒΆ
Example Code:
package main import ( "github.com/kataras/golog" "github.com/sirupsen/logrus" ) func main() { // outputOnly() full() } func full() { // simulate a logrus preparation: logrus.SetLevel(logrus.InfoLevel) logrus.SetFormatter(&logrus.JSONFormatter{}) // pass logrus.StandardLogger() to print logs using using the default, // package-level logrus' instance of Logger: golog.Install(logrus.StandardLogger()) golog.Debug(`this debug message will not be shown, because the logrus level is InfoLevel`) golog.Error("this error message will be visible as json") // simulate a change of the logrus formatter // as you see we have nothing more to change // on the golog, it works out of the box, // it will be adapt by this change, automatically. logrus.SetFormatter(&logrus.TextFormatter{}) golog.Error("this error message will be visible as text") golog.Info("this info message will be visible as text") } func outputOnly() { golog.SetOutput(logrus.StandardLogger().Out) golog.Info(`output only, this will print the same contents as golog but using the defined logrus' io.Writer`) golog.Error("this error message will be visible as text") }
Standard `log.Logger` Integration ΒΆ
Example Code:
package main import ( "log" "os" "github.com/kataras/golog" ) // simulate a log.Logger preparation: var myLogger = log.New(os.Stdout, "", 0) func main() { golog.SetLevel("error") golog.Install(myLogger) golog.Debug(`this debug message will not be shown, because the golog level is ErrorLevel`) golog.Error("this error message will be visible the only visible") golog.Warn("this info message will not be visible") }
That's the basics ΒΆ
But you should have a basic idea of the golog package by now, we just scratched the surface. If you enjoy what you just saw and want to learn more, please follow the below links:
Examples:
https://github.com/kataras/golog/tree/master/_examples
Index ΒΆ
- Constants
- 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 any)
- 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 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 any)
- 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) 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 ΒΆ
const Version = "0.1.12"
Version is the version string representation of the "golog" package.
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 ΒΆ added in v0.1.4
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 any)
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())
Or the standard log's Logger:
import "log" myLogger := log.New(os.Stdout, "", 0) Install(myLogger)
Or even the slog/log's Logger:
import "log/slog" myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) Install(myLogger) OR Install(slog.Default())
Look `golog#Logger.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 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`
func SetOutput ΒΆ
SetOutput overrides the Default Logger's Printer's output with another `io.Writer`.
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 ΒΆ added in v0.0.16
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 ΒΆ added in v0.1.5
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 ΒΆ added in v0.0.16
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 ΒΆ added in v0.0.16
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 ΒΆ added in v0.1.5
type JSONFormatter struct { Indent string // contains filtered or unexported fields }
JSONFormatter is a Formatter type for JSON logs.
func (*JSONFormatter) Format ΒΆ added in v0.1.5
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 ΒΆ added in v0.1.5
func (f *JSONFormatter) Options(opts ...interface{}) Formatter
Options sets the options for the JSON Formatter (currently only indent).
func (*JSONFormatter) String ΒΆ added in v0.1.5
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 ΒΆ added in v0.0.16
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.
func (*Log) FormatTime ΒΆ
FormatTime returns the formatted `Time`.
type Logger ΒΆ
type Logger struct { 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/kataras/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 LastChild ΒΆ added in v0.1.3
func LastChild() *Logger
LastChild returns the last registered child Logger.
func New ΒΆ
func New() *Logger
New returns a new golog with a default output to `os.Stdout` and level to `InfoLevel`.
func RegisterFormatter ΒΆ added in v0.1.5
RegisterFormatter registers a Formatter for this logger.
func SetChildPrefix ΒΆ added in v0.1.1
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 ΒΆ added in v0.1.5
SetLevelFormat changes the output format for the given "levelName".
func SetLevelOutput ΒΆ added in v0.1.3
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 ΒΆ added in v0.0.17
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 ΒΆ added in v0.1.4
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 ΒΆ
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())
Or the standard log's Logger:
import "log" myLogger := log.New(os.Stdout, "", 0) Install(myLogger)
Or even the slog/log's Logger:
import "log/slog" myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) Install(myLogger) OR Install(slog.Default())
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 ΒΆ added in v0.1.5
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 ΒΆ added in v0.1.1
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) 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 ΒΆ added in v0.1.5
SetLevelFormat changes the output format for the given "levelName".
func (*Logger) SetLevelOutput ΒΆ added in v0.1.3
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 ΒΆ added in v0.0.17
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 ΒΆ added in v0.0.14
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.
Source Files ΒΆ
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. |