2012-10-11 16 views
7

Estoy tratando de registrar la dirección IP del solicitante, qué MÉTODO están utilizando y qué archivo están solicitando. Pero por alguna razón que sólo produce la salida de la terminal y no guardarlo en logfile.txt ...Imprimir en el registro utilizando Go Language Simple HTTP Server

package main 

import (
    "fmt" 
    "net/http" 
    "log" 
    "encoding/json" 
    "io/ioutil" 
) 

type Options struct { 
    Path string 
    Port string 
} 

func Log(handler http.Handler) http.Handler { 
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 
    fmt.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL) 
    handler.ServeHTTP(w, r) 
    }) 
} 

func main() { 

    op := &Options{Path: "./", Port: "8001"} 

    data, _ := ioutil.ReadFile("./config.json") 

    json.Unmarshal(data, op) 

    http.Handle("/", http.FileServer(http.Dir(op.Path))) 
    err := http.ListenAndServe(":" + op.Port, Log(http.DefaultServeMux)) 
    if err != nil { 
    log.Fatal("ListenAndServe: ", err) 
    } 
} 
+2

La secuencia de comandos tal como está (el registro en la consola) es justo lo que necesitaba. –

Respuesta

7

En su función Log, que está utilizando no fmt.Printffmt.Fprintf.

Por ejemplo,

package main 

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

var logFile *os.File 

func Log(handler http.Handler) http.Handler { 
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 
     fmt.Fprintf(logFile, "%s %s %s\n", r.RemoteAddr, r.Method, r.URL) 
     handler.ServeHTTP(w, r) 
    }) 
} 

func main() { 
    var err error 
    logFile, err = os.Create("logfile.txt") 
    if err != nil { 
     log.Fatal("Log file create:", err) 
     return 
    } 
    defer logFile.Close() 
} 
+0

He añadido FprintF (w ... pero ¿cómo puedo dirigir eso a un archivo como logs.txt? (Gracias por la ayuda, por cierto) –

+0

Consulte mi respuesta revisada para obtener un resumen de una solución. – peterSO

Cuestiones relacionadas