Documentation ¶
Overview ¶
Package lcf (logrus-custom-formatter) is a customizable formatter for https://github.com/sirupsen/logrus that lets you choose which columns to include in your log outputs.
Windows Support ¶
Unlike Linux/OS X, Windows kind of doesn't support ANSI color codes. Windows versions before Windows 10 Insider Edition around May 2016 do not support ANSI color codes (instead your program is supposed to issue SetConsoleTextAttribute win32 API calls before each character to display if its color changes) and lcf will disable colors on those platforms by default. Windows version after that do actually support ANSI color codes but is disabled by default. lcf will detect this and disable colors by default if this feature (ENABLE_VIRTUAL_TERMINAL_PROCESSING) is not enabled.
You can enable ENABLE_VIRTUAL_TERMINAL_PROCESSING by calling lcf.WindowsEnableNativeANSI(true) in your program (logrus by default only outputs to stderr, call with false if you're printing to stdout instead). More information in the WindowsEnableNativeANSI documentation below.
Example Program ¶
Below is a simple example program that uses lcf with logrus:
package main import ( lcf "github.com/Robpol86/logrus-custom-formatter" "github.com/sirupsen/logrus" ) func main() { lcf.WindowsEnableNativeANSI(true) temp := "%[shortLevelName]s[%04[relativeCreated]d] %-45[message]s%[fields]s\n" logrus.SetFormatter(lcf.NewFormatter(temp, nil)) logrus.SetLevel(logrus.DebugLevel) animal := logrus.Fields{"animal": "walrus", "size": 10} logrus.WithFields(animal).Debug("A group of walrus emerges from the ocean") logrus.WithFields(animal).Warn("The group's number increased tremendously!") number := logrus.Fields{"number": 122, "omg": true} logrus.WithFields(number).Info("A giant walrus appears!") logrus.Error("Tremendously sized cow enters the ocean.") }
And the output is:
DEBU[0000] A group of walrus emerges from the ocean animal=walrus size=10 WARN[0000] The group's number increased tremendously! animal=walrus size=10 INFO[0000] A giant walrus appears! number=122 omg=true ERRO[0000] Tremendously sized cow enters the ocean.
Built-In Attributes ¶
These attributes are provided by lcf and can be specified in your template string:
%[ascTime]s Timestamp formatted by CustomFormatter.TimestampFormat. %[fields]s Logrus fields formatted as "key1=value key2=value". Keys are sorted unless CustomFormatter.DisableSorting is true. %[levelName]s The capitalized log level name (e.g. INFO, WARNING, ERROR). %[message]s The log message. %[name]s The value of the "name" field. If used "name" will be omitted from %[fields]s. %[process]d The current PID of the process emitting log statements. %[relativeCreated]d Number of seconds since the program has started (since formatter was created) %[shortLevelName]s Like %[levelName]s except WARNING is shown as "WARN".
Custom Handlers ¶
If what you're looking for is not available in the above built-in attributes or not exactly the functionality that you want you can add new or override existing attributes with custom handlers. Read the documentation for the CustomHandlers type below for more information.
Index ¶
- Constants
- func CallerName(skip int) string
- func Color(entry *logrus.Entry, formatter *CustomFormatter, s string) string
- func HandlerAscTime(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
- func HandlerFields(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
- func HandlerLevelName(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
- func HandlerMessage(entry *logrus.Entry, _ *CustomFormatter) (interface{}, error)
- func HandlerName(entry *logrus.Entry, _ *CustomFormatter) (interface{}, error)
- func HandlerProcess(_ *logrus.Entry, _ *CustomFormatter) (interface{}, error)
- func HandlerRelativeCreated(_ *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
- func HandlerShortLevelName(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
- func WindowsEnableNativeANSI(stderr bool) error
- func WindowsNativeANSI() bool
- type Attributes
- type CustomFormatter
- type CustomHandlers
- type Handler
Examples ¶
Constants ¶
const ( AnsiReset = 0 AnsiRed = 31 AnsiHiRed = 91 AnsiGreen = 32 AnsiHiGreen = 92 AnsiYellow = 33 AnsiHiYellow = 93 AnsiBlue = 34 AnsiHiBlue = 94 AnsiMagenta = 35 AnsiHiMagenta = 95 AnsiCyan = 36 AnsiHiCyan = 96 AnsiWhite = 37 AnsiHiWhite = 97 )
ANSI color codes.
const ( // Basic template just logs the level name, name field, message and fields. Basic = "%[levelName]s:%[name]s:%[message]s%[fields]s\n" // Message template just logs the message. Message = "%[message]s\n" // Detailed template logs padded columns including the running PID. Detailed = "%[ascTime]s %-5[process]d %-7[levelName]s %-20[name]s %[message]s%[fields]s\n" // DefaultTimestampFormat is the default format used if the user does not specify their own. DefaultTimestampFormat = "2006-01-02 15:04:05.000" // JMVoid custom time format JMVoidTimestampFormat = "2006-01-02 15:04:05" )
Variables ¶
This section is empty.
Functions ¶
func CallerName ¶
CallerName returns the name of the calling function using the runtime package. Empty string if something fails.
:param skip: Skip these many calls in the stack.
func Color ¶
func Color(entry *logrus.Entry, formatter *CustomFormatter, s string) string
Color colorizes the input string and returns it with ANSI color codes.
func HandlerAscTime ¶
func HandlerAscTime(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
HandlerAscTime returns the formatted timestamp of the entry.
func HandlerFields ¶
func HandlerFields(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
HandlerFields returns the entry's fields (excluding name field if %[name]s is used) colorized according to log level. Fields' formatting: key=value key2=value2
func HandlerLevelName ¶
func HandlerLevelName(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
HandlerLevelName returns the entry's long level name (e.g. "WARNING").
func HandlerMessage ¶
func HandlerMessage(entry *logrus.Entry, _ *CustomFormatter) (interface{}, error)
HandlerMessage returns the unformatted log message in the entry.
func HandlerName ¶
func HandlerName(entry *logrus.Entry, _ *CustomFormatter) (interface{}, error)
HandlerName returns the name field value set by the user in entry.Data.
func HandlerProcess ¶
func HandlerProcess(_ *logrus.Entry, _ *CustomFormatter) (interface{}, error)
HandlerProcess returns the current process' PID.
func HandlerRelativeCreated ¶
func HandlerRelativeCreated(_ *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
HandlerRelativeCreated returns the number of seconds since program start time.
func HandlerShortLevelName ¶
func HandlerShortLevelName(entry *logrus.Entry, formatter *CustomFormatter) (interface{}, error)
HandlerShortLevelName returns the first 4 letters of the entry's level name (e.g. "WARN").
func WindowsEnableNativeANSI ¶
WindowsEnableNativeANSI will attempt to set ENABLE_VIRTUAL_TERMINAL_PROCESSING on a console using SetConsoleMode.
:param stderr: Issue SetConsoleMode win32 API call on stderr instead of stdout handle.
func WindowsNativeANSI ¶
func WindowsNativeANSI() bool
WindowsNativeANSI returns true if either the stderr or stdout consoles natively support ANSI color codes. On non-Windows platforms this always returns false.
Types ¶
type Attributes ¶
Attributes is a map used like a "set" to keep track of which formatting attributes are used.
func (Attributes) Contains ¶
func (a Attributes) Contains(attr string) bool
Contains returns true if attr is present.
type CustomFormatter ¶
type CustomFormatter struct { // Post-processed formatting template (e.g. "%s:%s:%s\n"). Template string // Handler functions whose indexes match up with Template Sprintf explicit argument indexes. Handlers []Handler // Attribute names (e.g. "levelName") used in pre-processed Template. Attributes Attributes // Set to true to bypass checking for a TTY before outputting colors. ForceColors bool // Force disabling colors and bypass checking for a TTY. DisableColors bool // Timestamp format %[ascTime]s will use for display when a full timestamp is printed. TimestampFormat string // The fields are sorted by default for a consistent output. For applications // that log extremely frequently this may not be desired. DisableSorting bool // Different colors for different log levels. ColorDebug int ColorInfo int ColorWarn int ColorError int ColorFatal int ColorPanic int // contains filtered or unexported fields }
CustomFormatter is the main formatter for the library.
func NewFormatter ¶
func NewFormatter(template string, custom CustomHandlers) *CustomFormatter
NewFormatter creates a new CustomFormatter, sets the Template string, and returns its pointer. This function is usually called just once during a running program's lifetime.
:param template: Pre-processed formatting template (e.g. "%[message]s\n").
:param custom: User-defined formatters evaluated before built-in formatters. Keys are attributes to look for in the
formatting string (e.g. "%[myFormatter]s") and values are formatting functions.
func (*CustomFormatter) Format ¶
func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error)
Format is called by logrus and returns the formatted string.
func (*CustomFormatter) ParseTemplate ¶
func (f *CustomFormatter) ParseTemplate(template string, custom CustomHandlers)
ParseTemplate parses the template string and prepares it for fmt.Sprintf() and keeps track of which handlers to use.
:param template: Pre-processed formatting template (e.g. "%[message]s\n").
:param custom: User-defined formatters evaluated before built-in formatters. Keys are attributes to look for in the
func (*CustomFormatter) Sprintf ¶
func (f *CustomFormatter) Sprintf(values ...interface{}) string
Sprintf is like fmt.Sprintf() but exclude ANSI color sequences from string padding.
type CustomHandlers ¶
CustomHandlers is a mapping of Handler-type functions to attributes as key names (e.g. "levelName").
With this type many custom handler functions can be defined and fed to NewFormatter(). CustomHandlers are parsed first so you can override built-in handlers such as the one for %[ascTime]s with your own. Since they are exported you can call built-in handlers in your own custom handler. The returned interface{} value is passed to fmt.Sprintf().
In addition to overriding handlers you can create new attributes (such as %[myAttr]s) and map it to your Handler function.
Example ¶
// Define your own handler for new or to override built-in attributes. Here we'll // define LoadAverage() to handle a new %[loadAvg]f attribute. LoadAverage := func(e *logrus.Entry, f *CustomFormatter) (interface{}, error) { someNumber := 0.3 return someNumber, nil } // You can define additional formatting in the template string. Formatting is // handled by fmt.Sprintf() after lcf converts keyed indexes to integer indexes. template := "[%04[relativeCreated]d] %1.2[loadAvg]f %7[levelName]s %[message]s\n" formatter := NewFormatter(template, CustomHandlers{"loadAvg": LoadAverage}) // Create a new logger or use the standard logger. Here we'll create a new one // and configure it. log := logrus.New() log.Formatter = formatter log.Level = logrus.DebugLevel log.Out = os.Stdout log.Debug("A group of walrus emerges from the ocean") log.Warn("The group's number increased tremendously!") log.Info("A giant walrus appears!") log.Error("Tremendously sized cow enters the ocean.")
Output: [0000] 0.30 DEBUG A group of walrus emerges from the ocean [0000] 0.30 WARNING The group's number increased tremendously! [0000] 0.30 INFO A giant walrus appears! [0000] 0.30 ERROR Tremendously sized cow enters the ocean.