Logger
![Test](https://github.com/unrolled/logger/workflows/Test/badge.svg)
Logger is an HTTP middleware for Go that logs web requests to an io.Writer (the default being os.Stdout
). It's a standard net/http Handler, and can be used with many frameworks or directly with Go's net/http package.
Usage
package main
import (
"log"
"net/http"
"github.com/unrolled/logger"
)
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
})
func main() {
loggerWithConfigMiddleware := logger.New(logger.Options{
Prefix: "MySampleWebApp",
RemoteAddressHeaders: []string{"X-Forwarded-For"},
OutputFlags: log.LstdFlags,
})
app := loggerMiddleware.Handler(myHandler)
http.ListenAndServe("0.0.0.0:3000", app)
}
A simple GET request to "/info/" will output:
[MySampleWebApp] 2014/11/21 14:11:21 (12.34.56.78) "GET /info/ HTTP/1.1" 200 11 12.54µs
Here's a breakdown of what the values mean: [SuppliedPrefix] Date Time (RemoteIP) "Method RequestURI Protocol" StatusCode Size Time
.
Note that the Date Time
is controlled by the output flags. See http://golang.org/pkg/log/#pkg-constants.
Be sure to use the Logger middleware as the very first handler in the chain. This will ensure that your subsequent handlers (like Recovery) will always be logged.
Available Options
Logger comes with a variety of configuration options (Note: these are not the default option values. See the defaults below.):
l := logger.New(logger.Options{
Prefix: "myApp",
DisableAutoBrackets: false,
RemoteAddressHeaders: []string{"X-Forwarded-For"},
Out: os.Stdout,
OutputFlags: log.Ldate | log.Ltime,
IgnoredRequestURIs: []string{"/favicon.ico"},
})
Default Options
These are the preset options for Logger:
l := logger.New()
l := logger.New(logger.Options{
Prefix: "",
DisableAutoBrackets: false,
RemoteAddressHeaders: []string{},
Out: os.Stdout,
OutputFlags log.LstdFlags,
IgnoredRequestURIs: []string{},
})
Capturing the proper remote address
If your app is behind a load balancer or proxy, the default Request.RemoteAddr
will likely be wrong. To ensure you're logging the correct IP address, you can set the RemoteAddressHeaders
option to a list of header names you'd like to use. Logger will iterate over the slice and use the first header value it finds. If it finds none, it will default to the Request.RemoteAddr
.
package main
import (
"log"
"net/http"
"github.com/unrolled/logger"
)
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
})
func main() {
loggerWithConfigMiddleware := logger.New(logger.Options{
RemoteAddressHeaders: []string{"X-Real-IP", "X-Forwarded-For"},
})
app := loggerMiddleware.Handler(myHandler)
http.ListenAndServe("0.0.0.0:3000", app)
}