stats

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2016 License: MIT Imports: 11 Imported by: 11

README

Package stats

Project status Build Status GoDoc

Package stats allows for gathering of statistics regarding your Go application and system it is running on and sent them via UDP to a server where you can do whatever you wish to the stats; display, store in database or send off to a logging service.

  • of Garbabage collects

  • Last Garbage Collection
  • Last Garbage Collection Pause Duration
  • Memory Allocated
  • Memory Heap Allocated
  • Memory Heap System Allocated
  • Go version
  • Number of goroutines
  • HTTP request logging; when implemented via middleware
And the following System Information:
  • Host Information; hostname, OS....
  • CPU Information; type, model, # of cores...
  • Total CPU Timings
  • Per Core CPU Timings
  • Memory + Swap Information

Installation

Use go get.

go get gopkg.in/go-playground/stats.v1

or to update

go get -u gopkg.in/go-playground/stats.v1

Then import the validator package into your own code.

import "gopkg.in/go-playground/stats.v1"
Example

Server

package main

import (
	"fmt"

	"gopkg.in/go-playground/stats.v1"
)

func main() {

	config := &stats.ServerConfig{
		Domain: "",
		Port:   3008,
		Debug:  false,
	}

	server, err := stats.NewServer(config)
	if err != nil {
		panic(err)
	}

	for stat := range server.Run() {

		// calculate CPU times
		// totalCPUTimes := stat.CalculateTotalCPUTimes()
		// perCoreCPUTimes := stat.CalculateCPUTimes()

		// Do whatever you want with the data
		// * Save to database
		// * Stream elsewhere
		// * Print to console
		//

		fmt.Println(stat)
	}
}

Client

package main

import (
	"fmt"
	"net/http"
	"runtime"

	"gopkg.in/go-playground/stats.v1"
)

var statsClient *stats.ClientStats

func main() {

	serverConfig := &stats.ServerConfig{
		Domain: "remoteserver",
		Port:   3008,
		Debug:  false,
	}

	clientConfig := &stats.ClientConfig{
		Domain:           "",
		Port:             3009,
		PollInterval:     1000,
		Debug:            false,
		LogHostInfo:      true,
		LogCPUInfo:       true,
		LogTotalCPUTimes: true,
		LogPerCPUTimes:   true,
		LogMemory:        true,
		LogGoMemory:      true,
	}

	client, err := stats.NewClient(clientConfig, serverConfig)
	if err != nil {
		panic(err)
	}

	go client.Run()

	// if you want to capture HTTP requests in a middleware you'll have
	// to have access to the client.
	// see below for middleware example
	statsClient = client
}

// LoggingRecoveryHandler ...
//
//
// Middleware example for capturing HTTP Request info
// NOTE: this is standard go middlware, but could be adapted to other types/styles easily
//
func LoggingRecoveryHandler(next http.Handler) http.Handler {

	fn := func(w http.ResponseWriter, r *http.Request) {

		// log incoming request
		logReq := statsClient.NewHTTPRequest(w, r)

		defer func() {
			if err := recover(); err != nil {
				trace := make([]byte, 1<<16)
				n := runtime.Stack(trace, true)

				// log failure
				logReq.Failure(fmt.Sprintf("%s\n%s", err, trace[:n]))

				http.Error(w, "Friendly error message", 500)
				return
			}
		}()

		next.ServeHTTP(logReq.Writer(), r)

		// log completion
		logReq.Complete()
	}

	return http.HandlerFunc(fn)
}

License

  • MIT License, Copyright (c) 2015 Dean Karn
  • BSD License
    • Copyright (c) 2014, WAKAYAMA Shirou
    • Copyright (c) 2009 The Go Authors. All rights reserved.
  • BSD License, Copyright (c) 2010-2012 The w32 Authors. All rights reserved.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CPUInfo

type CPUInfo struct {
	CPU            []cpu.CPUInfoStat  `json:"cpu,omitempty"`
	PerCPUTimes    []cpu.CPUTimesStat `json:"percputimes,omitempty"`
	TotalTimes     []cpu.CPUTimesStat `json:"totaltimes,omitempty"`
	PrevCPUTimes   []cpu.CPUTimesStat `json:"prevpercputimes,omitempty"`
	PrevTotalTimes []cpu.CPUTimesStat `json:"prevtotaltimes,omitempty"`
}

CPUInfo contains CPU information

type CPUPercentages

type CPUPercentages struct {
	CPU       string
	User      float64
	System    float64
	Idle      float64
	Nice      float64
	IOWait    float64
	IRQ       float64
	SoftIRQ   float64
	Steal     float64
	Guest     float64
	GuestNice float64
	Stolen    float64
	Total     float64
}

CPUPercentages contains the CPU percentage information

type ClientConfig

type ClientConfig struct {
	Domain           string
	Port             int
	PollInterval     int
	Debug            bool
	LogHostInfo      bool
	LogCPUInfo       bool
	LogTotalCPUTimes bool
	LogPerCPUTimes   bool
	LogMemory        bool
	LogGoMemory      bool
	CustomBufferSize int
}

ClientConfig is used to initialize a new ClientStats object

type ClientStats

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

ClientStats is the object used to collect and send data to the server for processing

func NewClient

func NewClient(clientConfig *ClientConfig, serverConfig *ServerConfig) (*ClientStats, error)

NewClient create a new client object for use

func (*ClientStats) NewHTTPRequest

func (s *ClientStats) NewHTTPRequest(w http.ResponseWriter, r *http.Request) *HTTPRequest

NewHTTPRequest creates a new HTTPRequest for monitoring which wraps the ResponseWriter in order to collect stats so you need to call the Writer() function from the HTTPRequest created by this call

func (*ClientStats) Run

func (c *ClientStats) Run()

Run starts sending the profiling stats to the server NOTE: the server must be running prior to starting

func (*ClientStats) Stop

func (c *ClientStats) Stop()

Stop halts the client from sending any more data to the server, but may be run again at any time.

type GoInfo

type GoInfo struct {
	Version    string   `json:"gover"`
	Memory     GoMemory `json:"gomem"`
	GoRoutines int      `json:"goroutines"`
}

GoInfo contains go specific metrics and stats

type GoMemory

type GoMemory struct {
	NumGC               uint32 `json:"numgc"`
	LastGC              uint64 `json:"lastgc"`
	LastGCPauseDuration uint64 `json:"lastgcpause"`
	Alloc               uint64 `json:"alloc"`
	HeapAlloc           uint64 `json:"heap"`
	HeapSys             uint64 `json:"sys"`
	// contains filtered or unexported fields
}

GoMemory contains go specific memory metrics

type HTTPRequest

type HTTPRequest struct {
	URL                   string      `json:"url"`
	Method                string      `json:"method"`
	RequestContentLength  int64       `json:"reqContent"`
	Headers               http.Header `json:"headers"`
	Start                 time.Time   `json:"start"`
	End                   time.Time   `json:"end"`
	Duration              int64       `json:"duration"`
	ResponseContentLength int64       `json:"resContent"`
	StatusCode            int         `json:"status"`
	HasErrors             bool        `json:"hasErrs"`
	Error                 string      `json:"err"`
	// contains filtered or unexported fields
}

HTTPRequest contains information about the life of an http request

func (*HTTPRequest) Complete

func (r *HTTPRequest) Complete()

Complete finalizes an HTTPRequest and logs it.

func (*HTTPRequest) Failure

func (r *HTTPRequest) Failure(err string)

Failure records an HTTP failure and automatically completes the request

func (*HTTPRequest) Writer

func (r *HTTPRequest) Writer() http.ResponseWriter

Writer returns a wrapped http.ResponseWriter for logging purposes

type LogResponseWritter

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

LogResponseWritter wraps the standard http.ResponseWritter allowing for more verbose logging

func (*LogResponseWritter) Header

func (w *LogResponseWritter) Header() http.Header

Header returns & satisfies the http.ResponseWriter interface

func (*LogResponseWritter) Size

func (w *LogResponseWritter) Size() int

Size provides an easy way to retrieve the response size in bytes

func (*LogResponseWritter) Status

func (w *LogResponseWritter) Status() int

Status provides an easy way to retrieve the status code

func (*LogResponseWritter) Write

func (w *LogResponseWritter) Write(data []byte) (int, error)

Write satisfies the http.ResponseWriter interface and captures data written, in bytes

func (*LogResponseWritter) WriteHeader

func (w *LogResponseWritter) WriteHeader(statusCode int)

WriteHeader satisfies the http.ResponseWriter interface and allows us to cach the status code

type MemInfo

type MemInfo struct {
	Memory *mem.VirtualMemoryStat `json:"mem,omitempty"`
	Swap   *mem.SwapMemoryStat    `json:"swap,omitempty"`
}

MemInfo contains memory info including swap information

type ServerConfig

type ServerConfig struct {
	Domain           string
	Port             int
	Debug            bool
	CustomBufferSize int
}

ServerConfig is used to initialize a new ServerStats object

type ServerStats

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

ServerStats is the object used to receive, store and send data for usage

func NewServer

func NewServer(config *ServerConfig) (*ServerStats, error)

NewServer create a new server object for use

func (*ServerStats) Run

func (s *ServerStats) Run() <-chan *Stats

Run starts receiving the profiling stats for storage and usage

type Stats

type Stats struct {
	HostInfo     *host.HostInfoStat `json:"hostInfo,omitempty"`
	CPUInfo      *CPUInfo           `json:"cpu,omitempty"`
	MemInfo      *MemInfo           `json:"memInfo,omitempty"`
	GoInfo       *GoInfo            `json:"goInfo,omitempty"`
	HTTPRequests []*HTTPRequest     `json:"http"`
}

Stats contains all of the statistics to be passed and Encoded/Decoded on the Client and Server sides

func (*Stats) CalculateCPUTimes

func (s *Stats) CalculateCPUTimes() []CPUPercentages

CalculateCPUTimes calculates the total CPU times percentages per core

func (*Stats) CalculateTotalCPUTimes

func (s *Stats) CalculateTotalCPUTimes() []CPUPercentages

CalculateTotalCPUTimes calculates the total CPU times percentages

func (*Stats) GetAllCPUInfo

func (s *Stats) GetAllCPUInfo()

GetAllCPUInfo populates Stats with hosts CPU information and Timings

func (*Stats) GetCPUInfo

func (s *Stats) GetCPUInfo()

GetCPUInfo populates Stats with hosts CPU information

func (*Stats) GetCPUTimes

func (s *Stats) GetCPUTimes()

GetCPUTimes populates Stats with hosts CPU timing information

func (*Stats) GetHostInfo

func (s *Stats) GetHostInfo()

GetHostInfo populates Stats with host system information

func (*Stats) GetMemoryInfo

func (s *Stats) GetMemoryInfo(logMemory, logGoMemory bool)

GetMemoryInfo populates Stats with host and go process memory information

func (*Stats) GetTotalCPUTimes

func (s *Stats) GetTotalCPUTimes()

GetTotalCPUTimes populates Stats with hosts CPU timing information

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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