Improved logger
This commit is contained in:
parent
45f85d9a1e
commit
3cd8b403c5
@ -23,7 +23,11 @@ func IPToHost() aero.Middleware {
|
||||
func GetHostsForIP(ip string) []string {
|
||||
hosts, found := ipToHosts.Get(ip)
|
||||
|
||||
if !found || hosts == nil {
|
||||
if !found {
|
||||
hosts = findHostsForIP(ip)
|
||||
}
|
||||
|
||||
if hosts == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -31,17 +35,19 @@ func GetHostsForIP(ip string) []string {
|
||||
}
|
||||
|
||||
// Finds all host names for the given IP
|
||||
func findHostsForIP(ip string) {
|
||||
func findHostsForIP(ip string) []string {
|
||||
hosts, err := net.LookupAddr(ip)
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(hosts) == 0 {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cache host names
|
||||
ipToHosts.Set(ip, hosts, cache.DefaultExpiration)
|
||||
|
||||
return hosts
|
||||
}
|
||||
|
@ -12,26 +12,37 @@ import (
|
||||
"github.com/animenotifier/notify.moe/utils"
|
||||
)
|
||||
|
||||
// Log middleware logs every request into logs/request.log and errors into logs/error.log.
|
||||
func Log() aero.Middleware {
|
||||
request := log.New()
|
||||
var request = log.New()
|
||||
var err = log.New()
|
||||
|
||||
// Initialize log files
|
||||
func init() {
|
||||
request.AddOutput(log.File("logs/request.log"))
|
||||
|
||||
err := log.New()
|
||||
err.AddOutput(log.File("logs/error.log"))
|
||||
err.AddOutput(os.Stderr)
|
||||
}
|
||||
|
||||
// Log middleware logs every request into logs/request.log and errors into logs/error.log.
|
||||
func Log() aero.Middleware {
|
||||
return func(ctx *aero.Context, next func()) {
|
||||
start := time.Now()
|
||||
next()
|
||||
responseTime := time.Since(start)
|
||||
|
||||
go logRequest(ctx, responseTime)
|
||||
}
|
||||
}
|
||||
|
||||
// Logs a single request
|
||||
func logRequest(ctx *aero.Context, responseTime time.Duration) {
|
||||
responseTimeString := strconv.Itoa(int(responseTime.Nanoseconds()/1000000)) + " ms"
|
||||
responseTimeString = strings.Repeat(" ", 8-len(responseTimeString)) + responseTimeString
|
||||
|
||||
user := utils.GetUser(ctx)
|
||||
ip := ctx.RealIP()
|
||||
|
||||
hostName := ""
|
||||
hostName := "<unknown host>"
|
||||
hostNames := GetHostsForIP(ip)
|
||||
|
||||
if len(hostNames) != 0 {
|
||||
@ -59,5 +70,4 @@ func Log() aero.Middleware {
|
||||
if responseTime >= 200*time.Millisecond && !strings.HasPrefix(ctx.URI(), "/auth/") {
|
||||
err.Error("Long response time", ip, hostName, responseTimeString, ctx.StatusCode, ctx.URI())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user