astroflow

package module
v0.10.6 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2018 License: Apache-2.0 Imports: 11 Imported by: 0

README

Astroflow

Make logging great again

GoDoc Build Status GitHub release

Console logging

  1. Quickstart
  2. Benchmark
  3. Log usage
  4. Configuration
  5. HTTPHandler
  6. Roadmap

Quickstart

package main

import (
	"os"

	"github.com/bloom42/astroflow-go"
	"github.com/bloom42/astroflow-go/log"
)

func main() {

	env := os.Getenv("GO_ENV")
	hostname, _ := os.Hostname()

	log.Config(
		//   astroflow.SetWriter(os.Stderr),
		astroflow.AddFields(
			"service", "api",
			"host", hostname,
			"environment", env,
		),
		astroflow.SetFormatter(astroflow.NewConsoleFormatter()),
	)

	if env == "production" {
		log.Config(
			astroflow.SetFormatter(astroflow.JSONFormatter{}),
			astroflow.SetLevel(astroflow.InfoLevel),
		)
	}

	subLogger := log.With("contextual_field", 42)

	log.Info("info from logger")
	log.With("field1", "hello world", "field2", 999.99).Info("info from logger with fields")
	subLogger.Debug("debug from sublogger")
	subLogger.Warn("warning from sublogger")
	subLogger.Error("error from sublogger")
}

Benchmark

pkg: github.com/bloom42/astroflow-go/_benchmark
BenchmarkWithoutFields/sirupsen/logrus-4         	  500000	      3104 ns/op	    1473 B/op	      24 allocs/op
BenchmarkWithoutFields/bloom42/astroflow-go-4  	 1000000	      1454 ns/op	     664 B/op	       9 allocs/op
Benchmark10FieldsContext/sirupsen/logrus-4       	  100000	     12996 ns/op	    5680 B/op	      54 allocs/op
Benchmark10FieldsContext/bloom42/astroflow-go-4         	  300000	      5779 ns/op	    1934 B/op	      12 allocs/op
Benchmark10Fields/sirupsen/logrus-4                       	  100000	     14016 ns/op	    6393 B/op	      57 allocs/op
Benchmark10Fields/bloom42/astroflow-go-4                	  200000	      6038 ns/op	    2254 B/op	      13 allocs/op
PASS
ok  	github.com/bloom42/astroflow-go/_benchmark	9.120s

Log usage

import (
    "github.com/bloom42/astroflow-go/log"
)

log.Config(options ...astroflow.LoggerOption) error
log.With(fields ...interface{}) astro.Logger

// each of the following have it's XXXf companion (e.g. log.Debugf("%s" ,err) ...)
log.Debug(message string)
log.Info(message string)
log.Warn(message string)
log.Error(message string)
log.Fatal(message string) // log with the "fatal" level then os.Exit(1)

log.Track(fields ...interface{}) // log an event without level nor message

Configuration

SetWriter(writer io.Writer) // default to os.Stdout
SetFormatter(formatter astroflow.Formatter) // default to astro.JSONFormatter
SetFields(fields ...interface{})
AddFields(fields ...interface{})
SetInsertTimestampField(insert bool) // default to true
SetLevel(level Level) // default to astro.DebugLevel
SetTimestampFieldName(fieldName string) // default to astro.TimestampFieldName ("timestamp")
SetLevelFieldName(fieldName string) // default to astro.LevelFieldName ("level")
SetTimestampFunc(fn func() time.Time) // default to time.Now().UTC
AddHook(hook astro.Hook)

HTTPHandler

Astroflow provides an http handler helper to log http requests

package main

import (
	"fmt"
	"net/http"
	"os"

	"github.com/bloom42/astroflow-go"
	"github.com/bloom42/astroflow-go/log"
)

func main() {
	env := os.Getenv("GO_ENV")
	port := os.Getenv("PORT")
	if port == "" {
		port = "9090"
	}

	log.Config(
		astroflow.AddFields(
			"service", "api",
			"host", "abcd",
			"environment", env,
		),
		astroflow.SetFormatter(astroflow.JSONFormatter{}),
	)

	http.HandleFunc("/", HelloWorld)

	middleware := astroflow.HTTPHandler(log.With())
	err := http.ListenAndServe(":"+port, middleware(http.DefaultServeMux))
	if err != nil {
		log.Fatal(err.Error())
	}
}

func HelloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
}

Roadmap

  • method GetIP for the HTTPHandler to parse the IP form headers if trustProxy is set
  • SetAsync logger option
  • sampling
  • a zero alloc json logger (so without formatter)

Documentation

Overview

usage:

level := astro.DebugLevel
formatter := astro.ConsoleFormatter

if os.Gentenv("GO_ENV") == "production" {
	level = astro.InfoLevel
	formatter = astro.JSONFormatter
}

log.Config( // or log.Config
	astro.Token(...),
	astro.With({"app" "api"}, {"host": host}),
	astro.DisplayLogLevel(level),
	astro.Formatter(formatter),
	astro.Sample(sampler),
	// DisableTimeSTamp
	// default astro.SendLogLevel(astro.InfoLevel),
)

....

log.With("port", Port).Info("server stared")

```

Index

Constants

View Source
const (
	TimestampFieldName = "timestamp"
	MessageFieldName   = "message"
	LevelFieldName     = "level"
)
View Source
const (
	// Version is the astroflow's library version
	Version = "0.10.6"
)

Variables

This section is empty.

Functions

func HTTPHandler

func HTTPHandler(logger Logger) func(next http.Handler) http.Handler

Types

type CLIFormatter

type CLIFormatter struct {
	NoColor            bool
	TimestampFieldName string
	LevelFieldName     string
	MessageFieldName   string
}

func NewCLIFormatter

func NewCLIFormatter() CLIFormatter

func (CLIFormatter) Format

func (formatter CLIFormatter) Format(event Event) []byte

type ConsoleFormatter

type ConsoleFormatter struct {
	TimestampFieldName string
	MessageFieldName   string
	LevelFieldName     string
	NoColor            bool
}

func NewConsoleFormatter

func NewConsoleFormatter() ConsoleFormatter

func (ConsoleFormatter) Format

func (formatter ConsoleFormatter) Format(event Event) []byte

type Event

type Event map[string]interface{}

type Formatter

type Formatter interface {
	Format(entry Event) []byte
}

type Hook

type Hook func(event Event)

type JSONFormatter

type JSONFormatter struct{}

func (JSONFormatter) Format

func (formatter JSONFormatter) Format(entry Event) []byte

type Level

type Level int
const (
	DebugLevel Level = iota
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
	NoneLevel
	NoopLevel
)

type LogfmtFormatter

type LogfmtFormatter struct{}

func (LogfmtFormatter) Format

func (formatter LogfmtFormatter) Format(event Event) []byte

type Logger

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

func NewLogger

func NewLogger(options ...LoggerOption) Logger

NewLogger returns a new logger with default configuration. Additional can be provided

func (*Logger) Config

func (logger *Logger) Config(options ...LoggerOption) error

Config configure the logger

func (Logger) Debug

func (logger Logger) Debug(message string)

Debug level message

func (Logger) Debugf added in v0.10.0

func (logger Logger) Debugf(format string, a ...interface{})

Debugf level formatted message

func (Logger) Error

func (logger Logger) Error(message string)

Error level message

func (Logger) Errorf added in v0.10.0

func (logger Logger) Errorf(format string, a ...interface{})

Errorf error formatted message

func (Logger) Fatal

func (logger Logger) Fatal(message string)

Fatal message, followed by exit(1)

func (Logger) Fatalf added in v0.10.0

func (logger Logger) Fatalf(format string, a ...interface{})

Fatalf fatal formatted message, followed by exit(1)

func (Logger) Info

func (logger Logger) Info(message string)

Info level message

func (Logger) Infof added in v0.10.0

func (logger Logger) Infof(format string, a ...interface{})

Infof level formatted message

func (Logger) Track added in v0.6.0

func (logger Logger) Track(fields ...interface{})

Track an event without message nor level

func (Logger) Warn

func (logger Logger) Warn(message string)

Warn warning level message

func (Logger) Warnf added in v0.10.0

func (logger Logger) Warnf(format string, a ...interface{})

Warnf warning formatted message

func (Logger) With

func (logger Logger) With(fields ...interface{}) Logger

With returns a new Logger with the provided fields added

type LoggerOption

type LoggerOption func(logger *Logger) error

func AddFields

func AddFields(fields ...interface{}) LoggerOption

AddFields add the provided fields to the logger's internal fields

func AddHook

func AddHook(hook Hook) LoggerOption

func SetFields

func SetFields(fields ...interface{}) LoggerOption

SetFields replace the logger's internal fields with the provided fields

func SetFormatter

func SetFormatter(formatter Formatter) LoggerOption

func SetInsertTimestampField

func SetInsertTimestampField(insert bool) LoggerOption

func SetLevel

func SetLevel(level Level) LoggerOption

func SetLevelFieldName

func SetLevelFieldName(fieldName string) LoggerOption

func SetMessageFieldName

func SetMessageFieldName(fieldName string) LoggerOption

func SetTimestampFieldName

func SetTimestampFieldName(fieldName string) LoggerOption

func SetTimestampFunc

func SetTimestampFunc(fn func() time.Time) LoggerOption

func SetWriter

func SetWriter(writer io.Writer) LoggerOption

type StdoutWriter added in v0.6.0

type StdoutWriter struct{}

func (StdoutWriter) Write added in v0.6.0

func (writer StdoutWriter) Write(bytes []byte) (int, error)

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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