logger

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2020 License: MIT Imports: 16 Imported by: 3

README

Build Status GoDoc Go Report Card

Logger

Logger is a go library that provides a full featured logger. It has structured logging and color capabilities.

See the GoDoc for more information.

Installation

go get github.com/njones/logger

Example of how to use the Logger

package main

import (
	"github.com/njones/logger"
	"github.com/njones/logger/color"
)

var log = logger.New()

func main() {
	x := "xyz"
	user, emails := "someone", []string{"somewhere", "overtherainbow"}

	log.Debug("Starting the main function ...")

	// does something
	log.Warnf("Doing %s ...", x)

	// uses a custom color
	log.With(WithColor(color.Blue)).Info("This is info, but displays in BLUE ...")
	log.Info("instead of info being GREEN.")

	// uses structured logging
	log.Debug("The thing occurred here.", logger.KV("user", user), logger.KV("email", emails))
	logf := log.Field("user", user)
	logf.Debug("The thing occurred here.", logger.KV("email", emails)) // mix and match

	// can supress
	log.Supress(logger.Trace)
	log.Error("Finished with main.") // will show up
	log.Trace("Finished with main.") // won't show up

	// conditional log, will only log if there is an error
	err := doSomething()
	log.OnErr(err).Fatal("will log and exit on error: %v", logger.OnErr{}) // logger.OnErr{} is a placeholder for err 
	// log.Panic("will panic") will panic
}

License

Logger is available under the MIT License.

Copyright (c) 2017-2020 Nika Jones [email protected] All Rights Reserved.

Documentation

Overview

GENERATED BY ./gen/main.go; DO NOT EDIT THIS FILE ~~ This file is not generated by hand ~~ ~~ generated on: 2020-02-22 04:38:58.6751266 +0000 UTC m=+0.028521401 ~~

Index

Constants

View Source
const (
	Info  logLevel = 1 << iota //`short:"INF" color:"green"`
	Warn                       //`short:"WRN" color:"yellow"`
	Debug                      //`short:"DBG" color:"cyan"`
	Error                      //`short:"ERR" color:"magenta"`
	Trace                      //`short:"TRC" color:"blue"`
	Fatal                      //`short:"FAT" color:"red"`
	Panic                      //`short:"PAN" color:"red"`
	HTTP                       //`short:"-" long:"-" color:"-" fn:"ln"`
)

A bitwise representation of the different log levels NOTE: the comment tags are used when using go generate to generate parts of the logging code

View Source
const (
	Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
	Ltime                         // the time in the local time zone: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

All of the flags from the std log pkg

Variables

This section is empty.

Functions

func CommonLogFormat

func CommonLogFormat(now time.Time, status int, sent int64, tsText []byte, r *http.Request) string

CommonLogFormat is the Apache Common Logging format used for logging HTTP requests

func FilterWriter

func FilterWriter(w io.Writer, filters ...Filter) io.Writer

func NetWriter

func NetWriter(network, address string, opts ...nwOpt) io.Writer

NetWriter is a helper function that will log writes to a TCP/UDP address. Any errors will be written to stderr.

func NewLog

func NewLog(rxm rxMap, opts ...optFunc) *stdlog.Logger

func WithColor

func WithColor(v color.Foreground) optFunc

WithColor adds color to the logged output (overriding any level colors)

func WithHTTPHeader

func WithHTTPHeader(headers ...string) optFunc

WithHTTPHeader takes headers and addes them as a structured K/V pair to the logged output

func WithKVMarshaler

func WithKVMarshaler(fn func(interface{}) ([]byte, error)) optFunc

WithKVMarshaler takes a encoding.Marshaler interface and uses it to marshal kv values

func WithOutput

func WithOutput(ws ...io.Writer) optFunc

WithOutput adds the ws writers to the logged output. This can be overridden by using the logger.Output function. A nil or empty ws []io.Writer uses os.Stdout as the writer

func WithTimeFormat

func WithTimeFormat(format string, fns ...func(string) string) optFunc

WithTimeFormat formats the time according to the format value. Once the time has been formatted, it can apply any func(string)string function to the format, this can be used to uppercase the string (i.e. strings.ToUpper) for example. A empty value removes the time from the log output

func WithTimeText

func WithTimeText(text string) optFunc

WithTimeText replaces the timestamp value with the provided text, a empty value does not replace any timestamp formatted value

Types

type ErrSub

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

type Errer

type Errer interface{ Err() error }

type ExtendedLogger

type ExtendedLogger interface {
	StandardLogger

	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Infoln(v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
	Warnln(v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Errorln(v ...interface{})
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Debugln(v ...interface{})
	Trace(v ...interface{})
	Tracef(format string, v ...interface{})
	Traceln(v ...interface{})
}

ExtendedLogger the interface that defines the extra log levels outside of the std log package logging.

type Filter

type Filter interface {
	Check(string) bool
}

Filter defines the intterface for checking if a log line should be logged based on a true value from the filter Check(string) function

func NotFilter

func NotFilter(filter Filter) Filter

NotFilter negates the check on the wrapped filter

func RegexFilter

func RegexFilter(pattern string) Filter

RegexFilter is a filter function that takes a regular expresson and if it is matched by the logline then that line is filtered out

func StringFuncFilter

func StringFuncFilter(fn func(string) bool) Filter

StringFuncFilter is a filter function that takes the function func(string)bool with any returned true value, filtering out the log line, so it will not display.

type HTTPLogFormatFunc

type HTTPLogFormatFunc func(time.Time, int, int64, []byte, *http.Request) string

HTTPLogFormatFunc is the type that is used for logging HTTP requests

type HTTPLogger

type HTTPLogger interface {
	HTTPMiddleware(http.Handler) http.Handler
}

HTTPLogger the interface that defines HTTP logging that can be inserted as middleware in HTTP routers

type K

type K string

The Key-Value types

type KVMap

type KVMap map[K]V

The Key-Value types

type KeyVal

type KeyVal struct {
	Key   K `json:"key"`
	Value V `json:"value"`
}

The Key-Value types

func KV

func KV(k K, v V) KeyVal

type Logger

type Logger interface {
	ExtendedLogger
	HTTPLogger

	OnErr(error) OnErrLogger

	FatalInt(int) Logger
	Field(string, interface{}) Logger
	Fields(map[string]interface{}) Logger
	Suppress(logLevel) Logger
	With(...optFunc) Logger
}

Logger the interface that defines the logger package functions

func New

func New(opts ...optFunc) Logger

type NoColorWriter

type NoColorWriter interface {
	NoColor()
}

type OnErrLogger

type OnErrLogger interface {
	StandardOptions

	// from the standard logger
	Print(v ...interface{}) Return
	Printf(format string, v ...interface{}) Return
	Println(v ...interface{}) Return
	Fatal(v ...interface{}) Return
	Fatalf(format string, v ...interface{}) Return
	Fatalln(v ...interface{}) Return
	Panic(v ...interface{}) Return
	Panicf(format string, v ...interface{}) Return
	Panicln(v ...interface{}) Return

	// from the extended logger
	Info(v ...interface{}) Return
	Infof(format string, v ...interface{}) Return
	Infoln(v ...interface{}) Return
	Warn(v ...interface{}) Return
	Warnf(format string, v ...interface{}) Return
	Warnln(v ...interface{}) Return
	Error(v ...interface{}) Return
	Errorf(format string, v ...interface{}) Return
	Errorln(v ...interface{}) Return
	Debug(v ...interface{}) Return
	Debugf(format string, v ...interface{}) Return
	Debugln(v ...interface{}) Return
	Trace(v ...interface{}) Return
	Tracef(format string, v ...interface{}) Return
	Traceln(v ...interface{}) Return
}

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriter holds an embedded HTTP ResponseWriter but will capture the status and number of bytes sent so they can be logged.

func (*ResponseWriter) Write

func (c *ResponseWriter) Write(p []byte) (n int, err error)

Write writes to the underlining write, while counting the number of bytes that pass through

func (*ResponseWriter) WriteHeader

func (c *ResponseWriter) WriteHeader(code int)

WriteHeader captures the status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK).

type Return

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

func (Return) Err

func (rtn Return) Err() error

func (Return) HasErr

func (rtn Return) HasErr() bool

type StandardLogger

type StandardLogger interface {
	StandardOptions

	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
}

StandardLogger the interface that matches the std library log package

type StandardOptions

type StandardOptions interface {
	Flags() int
	Output(calldepth int, s string) error
	Prefix() string
	SetFlags(flag int)
	SetOutput(w io.Writer)
	SetPrefix(prefix string)
	Writer() io.Writer
}

StandardOptions the interface that matches the std library log package functions outside of Fatal(x), Print(x) and Panic(x).

type V

type V interface{}

The Key-Value types

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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