2015-09-12 13:10:03 +00:00
|
|
|
/*
|
|
|
|
Copyright
|
|
|
|
*/
|
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2015-09-24 15:16:13 +00:00
|
|
|
|
|
|
|
"github.com/gorilla/handlers"
|
2015-09-12 13:10:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Logger is a middleware handler that logs the request as it goes in and the response as it goes out.
|
|
|
|
type Logger struct {
|
|
|
|
file *os.File
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewLogger returns a new Logger instance
|
|
|
|
func NewLogger(file string) *Logger {
|
2015-09-15 20:32:09 +00:00
|
|
|
if len(file) > 0 {
|
|
|
|
fi, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
|
2015-09-12 13:10:03 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Error opening file", err)
|
|
|
|
}
|
|
|
|
return &Logger{fi}
|
|
|
|
}
|
2015-09-24 15:16:13 +00:00
|
|
|
return &Logger{nil}
|
2015-09-12 13:10:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
2015-09-15 20:32:09 +00:00
|
|
|
if l.file == nil {
|
2015-09-12 13:10:03 +00:00
|
|
|
next(rw, r)
|
2015-09-15 20:32:09 +00:00
|
|
|
} else {
|
2015-09-12 13:10:03 +00:00
|
|
|
handlers.CombinedLoggingHandler(l.file, next).ServeHTTP(rw, r)
|
|
|
|
}
|
2015-09-12 13:20:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *Logger) Close() {
|
|
|
|
l.file.Close()
|
2015-09-15 20:32:09 +00:00
|
|
|
}
|