GithubHelp home page GithubHelp logo

thoas / stats Goto Github PK

View Code? Open in Web Editor NEW
595.0 17.0 53.0 3.47 MB

A Go middleware that stores various information about your web application (response time, status code count, etc.)

License: MIT License

Go 99.75% Makefile 0.25%

stats's Introduction

Go stats handler

Build Status

stats is a net/http handler in golang reporting various metrics about your web application.

This middleware has been developed and required for the need of picfit, an image resizing server written in Go.

Compatibility

This handler supports the following frameworks at the moment:

We don't support your favorite Go framework? Send me a PR or create a new issue and I will implement it :)

Installation

  1. Make sure you have a Go language compiler >= 1.3 (required) and git installed.
  2. Make sure you have the following go system dependencies in your $PATH: bzr, svn, hg, git
  3. Ensure your GOPATH is properly set.
  4. Download it:
go get github.com/thoas/stats

Usage

Basic net/http

To use this handler directly with net/http, you need to call the middleware with the handler itself:

package main

import (
    "net/http"
    "github.com/thoas/stats"
)

func main() {
    h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })

    handler := stats.New().Handler(h)
    http.ListenAndServe(":8080", handler)
}

Negroni

If you are using negroni you can implement the handler as a simple middleware in server.go:

package main

import (
    "net/http"
    "github.com/codegangsta/negroni"
    "github.com/thoas/stats"
    "encoding/json"
)

func main() {
    middleware := stats.New()

    mux := http.NewServeMux()

    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })

    mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")

        stats := middleware.Data()

        b, _ := json.Marshal(stats)

        w.Write(b)
    })

    n := negroni.Classic()
    n.Use(middleware)
    n.UseHandler(mux)
    n.Run(":3000")
}

HTTPRouter .......

If you are using HTTPRouter you need to call the middleware with the handler itself:

package main                                                                          

import (
        "encoding/json"
        "github.com/julienschmidt/httprouter"
        "github.com/thoas/stats"
        "net/http"
)

func main() {
        router := httprouter.New()
        s := stats.New()
        router.GET("/stats", func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
                w.Header().Set("Content-Type", "application/json; charset=utf-8")
                s, err := json.Marshal(s.Data())
                if err != nil {
                        http.Error(w, err.Error(), http.StatusInternalServerError)
                }
                w.Write(s)
        })
        http.ListenAndServe(":8080", s.Handler(router))
}

Martini

If you are using martini, you can implement the handler as a wrapper of a Martini.Context in server.go:

package main

import (
    "encoding/json"
    "github.com/go-martini/martini"
    "github.com/thoas/stats"
    "net/http"
)

func main() {
    middleware := stats.New()

    m := martini.Classic()
    m.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })
    m.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")

        stats := middleware.Data()

        b, _ := json.Marshal(stats)

        w.Write(b)
    })

    m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
        beginning, recorder := middleware.Begin(w)

        c.Next()

        middleware.End(beginning, stats.WithRecorder(recorder))
    })
    m.Run()
}

Run it in a shell:

$ go run server.go

Then in another shell run:

$ curl http://localhost:3000/stats | python -m "json.tool"

Expect the following result:

{
    "total_response_time": "1.907382ms",
    "average_response_time": "86.699\u00b5s",
    "average_response_time_sec": 8.6699e-05,
    "count": 1,
    "pid": 99894,
    "status_code_count": {
        "200": 1
    },
    "time": "2015-03-06 17:23:27.000677896 +0100 CET",
    "total_count": 22,
    "total_response_time_sec": 0.0019073820000000002,
    "total_status_code_count": {
        "200": 22
    },
    "unixtime": 1425659007,
    "uptime": "4m14.502271612s",
    "uptime_sec": 254.502271612
}

See examples to test them.

Inspiration

Antoine Imbert is the original author of this middleware.

Originally developed for go-json-rest, it had been ported as a simple Golang handler by Florent Messa to be used in various frameworks.

This middleware implements a ticker which is launched every seconds to reset requests/sec and will implement new features in a near future :)

stats's People

Contributors

appleboy avatar caarlos0 avatar caglar10ur avatar codelingobot avatar e-max avatar johntdyer avatar juliens avatar keizo042 avatar ldez avatar mattn avatar mindscratch avatar pomyk avatar siyu6974 avatar thoas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stats's Issues

Latest check in breaks my build

I'm using your fine package in a small app thats a go module, when I did a go get -u I get the error:
options.go:55:4: o.saveResult undefined (type *Options has no field or method saveResult)

While this is not a problem, it would be advantageous if you could tag a release or - even better - use Git flow to ensure we can keep using your package as you develop.

Data method is not thread safe.

Though this method is protected by lock and create a new structure on every call, this structure still use the same instance of ResponseCounts. So it is possible that somebody would read this map in the same moment as EndWithStatus would write into it.
In go 1.6 it will cause a panic.

Example for Gin doesn't work (anymore?)

image

main.go:35: cannot use c.Writer (type gin.ResponseWriter) as type stats.ResponseWriter in argument to Stats.End:
        gin.ResponseWriter does not implement stats.ResponseWriter (missing Before method)
FATAL: command "build" failed: exit status 2

wrong status code of middleware

the example of gin should be:

// StatMiddleware response time, status code count, etc.
func StatMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        beginning, _ := Stats.Begin(c.Writer)
        c.Next()
        Stats.EndWithStatus(beginning, c.Writer.Status())
    }
}

the example of martini has same issue

Possible false response code

if we look at https://github.com/thoas/stats/blob/master/recorder.go#L39 and take following scenario:

func (r *recorderResponseWriter) WriteHeader(code int) {
	r.written = true
	r.ResponseWriter.WriteHeader(code)
	r.status = code
}
  1. We write header 200. :: r.status=200, r.ResponseWriter.status=200
  2. We write header 200. :: r.status=300, r.ResponseWriter.status=200
    in step 2 internal response writer ignores new status code.

ref:

if I understood the issue correctly and if it really is a genuine issue, happy to make a PR

Is prometheus supported?

Hi,

I want to know it the result of stats.Data() has a format supported by Prometheus.

Thanks

use martini status_code_count and total_status_code_count code question,

{
"pid": 27613,
"uptime": "2m7.358545583s",
"uptime_sec": 127.358545583,
"time": "2016-11-10 14:45:35.526270515 +0800 CST",
"unixtime": 1478760335,
"status_code_count": {
"200": 1
},
"total_status_code_count": {
"200": 17
},
"count": 1,
"total_count": 17,
"total_response_time": "78.531534ms",
"total_response_time_sec": 0.078531534,
"average_response_time": "4.619502ms",
"average_response_time_sec": 0.004619502
}

status_code_count and total_status_code_count code always 200, reivew the code , it is hard-coded. so I think the statecode should be depend on w.
func (mw *Stats) Begin(w http.ResponseWriter) (time.Time, ResponseWriter) {
start := time.Now()

writer := NewRecorderResponseWriter(w, 200)

return start, writer

}

Bogus HTTP response status code stats

Hi

I'm observing what looks to be a bogus behavior of your middleware regarding the counting of HTTP responses status code. Given the following implementation with Negroni:

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/gorilla/mux"
	"github.com/thoas/stats"
	"github.com/urfave/negroni"
)

func main() {
	router := mux.NewRouter()
	httpStats := stats.New()

	router.HandleFunc("/a", handleA).
		Methods("GET", "POST", "PUT")

	router.HandleFunc("/b", handleB).
		Methods("GET")

	router.HandleFunc("/c", handleC).
		Methods("GET")

	router.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		stats := httpStats.Data()
		b, _ := json.Marshal(stats)
		w.Write(b)
	})

	n := negroni.New()

	n.UseHandler(router)
	n.Use(httpStats)

	http.ListenAndServe(":8000", n)
}

func handleA(rw http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST", "PUT":
		time.Sleep(100 * time.Millisecond)
		rw.WriteHeader(http.StatusCreated)

	case "GET":
		time.Sleep(10 * time.Millisecond)
	}

	fmt.Fprintf(rw, "A\n")
}

func handleB(rw http.ResponseWriter, r *http.Request) {
	time.Sleep(50 * time.Millisecond)
	fmt.Fprintf(rw, "B\n")
}

func handleC(rw http.ResponseWriter, r *http.Request) {
	time.Sleep(10 * time.Millisecond)
	fmt.Fprintf(rw, "C\n")
}

Sending the following HTTP requests...

$ curl -i -X POST localhost:8000/a
HTTP/1.1 201 Created
Date: Mon, 18 Dec 2017 15:16:25 GMT
Content-Length: 2
Content-Type: text/plain; charset=utf-8

A

$ curl -i -X POST localhost:8000/b
HTTP/1.1 405 Method Not Allowed
Date: Mon, 18 Dec 2017 15:16:32 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8

$ curl -i localhost:8000/c
HTTP/1.1 200 OK
Date: Mon, 18 Dec 2017 15:16:40 GMT
Content-Length: 2
Content-Type: text/plain; charset=utf-8

C

$ curl -i localhost:8000/z
HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Mon, 18 Dec 2017 15:16:42 GMT
Content-Length: 19

404 page not found

...I expected the /stats response total_status_code_count value to be {"200":1,"201":1,"404":1,"405":1}, but it's not:

$ curl localhost:8000/stats | jq .
{
  "pid": 7201,
  "uptime": "46.962268141s",
  "uptime_sec": 46.962268141,
  "time": "2017-12-18 16:16:55.098574 +0100 CET m=+46.963702150",
  "unixtime": 1513610215,
  "status_code_count": {},
  "total_status_code_count": {
    "200": 4
  },
  "count": 0,
  "total_count": 4,
  "total_response_time": "13.083µs",
  "total_response_time_sec": 1.3083e-05,
  "average_response_time": "3.27µs",
  "average_response_time_sec": 3.27e-06
}

Am I doing something wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.