golang的http服务添加请求日志

2022-07-31  本文已影响0人  深圳都这么冷

需求

net/http写的http服务,没有任何日志,现在需要添加请求日志,每次http请求时在标准输出打印一行日志

自己实现

package main

import (
    "log"
    "net/http"
    "os"
    "time"
)

func RequestLogger(targetMux http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        targetMux.ServeHTTP(w, r)
        log.Printf(
            "%s\t\t%s\t\t%s\t\t%v",
            r.Method,
            r.RequestURI,
            r.RemoteAddr,
            time.Since(start),
        )
    })
}

func SayGoodByeWorld(w http.ResponseWriter, r *http.Request) {
    html := "Good Bye World"
    w.Write([]byte(html))
}

func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
    html := "Hello World"
    w.Write([]byte(html))
}

func main() {
    log.SetOutput(os.Stdout)

    http.HandleFunc("/hi", SayHelloWorld)
    http.HandleFunc("/bye", SayGoodByeWorld)

    http.ListenAndServe(":8080", RequestLogger(http.DefaultServeMux))
}

输入如下

 $ go run main.go
2022/08/01 20:04:19 GET     /hi     [::1]:52536     8.799µs
2022/08/01 20:04:19 GET     /favicon.ico        [::1]:52536     28.961µs
2022/08/01 20:04:21 GET     /bye?a=b&c=d        [::1]:52536     5.467µs

第三方库

https://github.com/gorilla/handlers

http.ListenAndServe(":19888", nil)

改为

import "github.com/gorilla/handlers"
http.ListenAndServe(":19888", handlers.LoggingHandler(os.Stdout, http.DefaultServeMux))

输入如下

10.90.34.133 - - [01/Aug/2022:12:02:11 +0000] "GET /devtestops/devtoapi/workflow/logs?team=framework&flowId=devtestops-ci-devto-server-xmjph HTTP/1.1" 200 1575
10.90.34.133 - - [01/Aug/2022:12:02:12 +0000] "GET /devtestops/devtoapi/workflow/logs?team=framework&flowId=devtestops-ci-devto-server-xmjph HTTP/1.1" 200 1575
上一篇下一篇

猜你喜欢

热点阅读