logjam

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: May 6, 2020 License: MIT Imports: 23 Imported by: 0

README

Logjam client for Go

GoDoc Travis

This package provides integration with the Logjam monitoring tool for Go web-applications.

It buffers all log output for a request and sends the result to a configured logjam device when the request was finished.

Requirements

This package depends on github.com/pebbe/zmq4 which requires ZeroMQ version 4.0.1 or above. Make sure you have it installed on your machine.

E.g. for MacOS:

brew install zmq

How to use it

Install via go get github.com/xing/logjam-agent-go.

Initialize the client
logjam.SetupAgent(&logjam.Options{
	AppName: "MyApp",
	EnvName: "production",
	Logger:	 log.New(os.Stderr, "API", log.LstdFlags),
)
Use the logjam middleware
r := mux.NewRouter()
...
r.Use(logjam.NewMiddleware(r))
...

This example uses the Gorilla Mux package but it should also work with other router packages.

You also need to set environment variables to point to the actual logjam broker instance:

export LOGJAM_BROKER=my-logjam-broker.host.name

Shutting down

Make sure to shut down the agent upon program termination in order to properly close the ZeroMQ socket used to send messages to logjam.

logjam.ShutdownAgent()
Adapting logjam action names

By default, the logjam middleware fabricates logjam action names from the escaped request path and request method. For example, a GET request to the endpoint "/users/123/friends" will be translated to "Users::Id::Friends#get". If you're not happy with that, you can override the action name in your request handler, as the associated logjam request is available from the request context:

func ShowFriends(w http.ResponseWriter, r *http.Request) {
	request := logjam.GetRequest(r)
	request.ChangeAction(w, "Users#friends")
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

If you're using the gorilla mux package, you can configure the desired logjam action name when declaring the route. The following examples uses a Rails inspired naming:

import ("github.com/xing/logjam-agent-go/gorilla")

gorilla.ActionName(router.Path("/users").Methods("GET").HandlerFunc(...), "Users#index")
gorilla.ActionName(router.Path("/users").Methods("POST").HandlerFunc(...), "Users#create")
gorilla.ActionName(router.Path("/users/{user_id}").Methods("GET").HandlerFunc(...), "Users#show")
gorilla.ActionName(router.Path("/users/{user_id}").Methods("PUT", "PATCH").HandlerFunc(...), "Users#update")
gorilla.ActionName(router.Path("/users/{user_id}").Methods("DELETE").HandlerFunc(...), "Users#destroy")
gorilla.ActionName(router.Path("/users/{user_id}/friends").Methods("GET").HandlerFunc(...), "Users#friends")

Make sure to have the route fully configured before calling gorilla.ActionName.

Hot to contribute?

Please fork the repository and create a pull-request for us.

Documentation

Overview

Package logjam provides a go client for sending application metrics and log lines to a logjam endpoint. See https://github.com/skaes/logjam_app.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultActionNameExtractor

func DefaultActionNameExtractor(r *http.Request) string

DefaultActionNameExtractor replaces slashes with "::" and camel cases the individual path segments.

func LegacyActionNameExtractor

func LegacyActionNameExtractor(r *http.Request) string

LegacyActionNameExtractor is an extractor used in older versions of this package. Use it if you want to keep old action names in Logjam.

func Log

func Log(hc HasContext, severity LogLevel, format string, args ...interface{})

Log takes a context to be able to collect all logs within the same request. If you're using gin-gonic, please pass the (*gin.Context).Request.Context() Maximum line length is 2048 characters.

func LogDebug

func LogDebug(hc HasContext, format string, args ...interface{})

LogDebug calls Log with DEBUG severity.

func LogError

func LogError(hc HasContext, format string, args ...interface{})

LogError calls Log with ERROR severity.

func LogFatal

func LogFatal(hc HasContext, format string, args ...interface{})

LogFatal calls Log with FATAL severity.

func LogInfo

func LogInfo(hc HasContext, format string, args ...interface{})

LogInfo calls Log with INFO severity.

func LogWarn

func LogWarn(hc HasContext, format string, args ...interface{})

LogWarn calls Log with WARN severity.

func NewMiddleware

func NewMiddleware(handler http.Handler) http.Handler

NewMiddleware can be used to wrap any standard http.Handler.

func SetCallHeaders added in v0.0.7

func SetCallHeaders(hc HasContext, outgoing *http.Request)

SetCallHeaders makes sure all X-Logjam-* Headers are copied into the outgoing request. Call this before you call other APIs.

func SetupAgent

func SetupAgent(options *Options)

SetupAgent configures application name, environment name and ZeroMQ socket options.

func ShutdownAgent

func ShutdownAgent()

ShutdownAgent closes the ZeroMQ socket

Types

type ActionNameExtractor

type ActionNameExtractor func(*http.Request) string

ActionNameExtractor takes a HTTP request and returns a logjam conformant action name.

type HasContext

type HasContext interface {
	Context() context.Context
}

HasContext is any object that reponds to the Context method.

type LogLevel

type LogLevel int

LogLevel (modeled afterRuby log levels).

const (
	DEBUG LogLevel = 0
	INFO  LogLevel = 1
	WARN  LogLevel = 2
	ERROR LogLevel = 3
	FATAL LogLevel = 4
)

type Logger

type Logger interface {
	Println(v ...interface{})
	Printf(fmt string, v ...interface{})
}

Logger must provide some methods to let Logjam output its logs.

type Options added in v0.0.7

type Options struct {
	AppName             string              // Name of your application
	EnvName             string              // What environment you're running in (production, preview, ...)
	Endpoints           string              // Comma separated list of ZeroMQ connections specs, defaults to localhost
	Port                int                 // ZeroMQ default port for ceonnection specs
	Linger              int                 // ZeroMQ socket option of the same name
	Sndhwm              int                 // ZeroMQ socket option of the same name
	Rcvhwm              int                 // ZeroMQ socket option of the same name
	Sndtimeo            int                 // ZeroMQ socket option of the same name
	Rcvtimeo            int                 // ZeroMQ socket option of the same name
	Logger              Logger              // TODO: why is this an option?
	ActionNameExtractor ActionNameExtractor // Function to transform path segments to logjam action names.
	ObfuscateIPs        bool                // Whether IPa addresses should be obfuscated.
	MaxLineLength       int                 // Long lines truncation threshold, defaults to 2048.
	MaxBytesAllLines    int                 // Max number of bytes of all log lines, defaults to 1MB.
}

Options such as appliction name, environment and ZeroMQ socket options.

type Request

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

Request encapsulates information about the current logjam request.

func GetRequest

func GetRequest(hc HasContext) *Request

GetRequest retrieves a logjam request from an object with Context. Returns nil if no request is stored in the context.

func NewRequest

func NewRequest(action string) *Request

NewRequest creates a new logjam request for a given action name.

func (*Request) AddCount

func (r *Request) AddCount(key string, value int64)

AddCount increments a counter metric associated with this request.

func (*Request) AddDuration

func (r *Request) AddDuration(key string, value time.Duration)

AddDuration increases increments a timer metric associated with this request.

func (*Request) AugmentRequest

func (r *Request) AugmentRequest(incoming *http.Request) *http.Request

AugmentRequest extends a given http request with a logjam request stored in its context.

func (*Request) ChangeAction added in v0.0.6

func (r *Request) ChangeAction(w http.ResponseWriter, action string)

ChangeAction changes the action name and updates the corresponding header on the given http request writer.

func (*Request) Count

func (r *Request) Count(key string)

Count behaves like AddCount with a value of 1

func (*Request) Finish

func (r *Request) Finish(code int)

Finish adds the response code to the requests and sends it to logjam.

func (*Request) GetField

func (r *Request) GetField(key string) interface{}

GetField retrieves sets an additional key value pair on the request.

func (*Request) Log added in v0.0.3

func (r *Request) Log(severity LogLevel, line string)

Log adds a log line to be sent to logjam to the request.

func (*Request) MeasureDuration

func (r *Request) MeasureDuration(key string, f func())

MeasureDuration is a helper function that records the duration of execution of the passed function in cases where it is cumbersome to just use AddDuration instead.

func (*Request) NewContext

func (r *Request) NewContext(c context.Context) context.Context

NewContext creates a new context with the request added.

func (*Request) SetField

func (r *Request) SetField(key string, value interface{})

SetField sets an additional key value pair on the request.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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