大猩猩处理程序写入文件

时间:2015-04-13 10:48:49

标签: http go

import (
    "github.com/gorilla/handlers"
)

func main(){
    ...

    err := http.ListenAndServe(":9000", access_log(r))
    if err != nil {
        log.Fatal("HTTP server: ", err)
    }
}

func access_log(r http.Handler) http.Handler {
    f, err := os.OpenFile("log/access.log", os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666)
    if err != nil {
        log.Panic("Access log: ", err)
    }

    return handlers.LoggingHandler(io.Writer(f), r)
}

文件已创建,但每次请求都没有写入文件

更新

当输出写入os.Stdout

时,此方法有效
func access_log(r http.Handler) http.Handler {
    /*f, err := os.OpenFile("log/access.log", os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666)
    if err != nil {
        log.Panic("Access log: ", err)
    }

    return handlers.LoggingHandler(io.Writer(f), r)*/

    return handlers.LoggingHandler(os.Stdout, r)
}

更新II

func main(){
    runtime.GOMAXPROCS(runtime.NumCPU())

    r := mux.NewRouter()

    www := r.Host("secure.domain.com").Subrouter()
    www.HandleFunc("/", Handler_www)

    api := r.Host("api.domain.com").Subrouter()
    api.HandleFunc("/", Handler_api)

    err := http.ListenAndServe(":9000", access_log(r))
    if err != nil {
        log.Fatal("HTTP server: ", err)
    }
}

func access_log(r http.Handler) http.Handler {
    f, err := os.OpenFile("log/access.log", os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666)
    if err != nil {
        log.Panic("Access log: ", err)
    }

    return handlers.LoggingHandler(f, r)
}

0 个答案:

没有答案