Il s'agit d'un simple enregistreur
package customlogger
import (
"log"
"os"
"sync"
)
type logger struct {
filename string
*log.Logger
}
var logger *logger
var once sync.Once
// start loggeando
func GetInstance() *logger {
once.Do(func() {
logger = createLogger("mylogger.log")
})
return logger
}
func createLogger(fname string) *logger {
file, _ := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
return &logger{
filename: fname,
Logger: log.New(file, "My app Name ", log.Lshortfile),
}
}
Vous pouvez l'utiliser de la manière suivante
package main
import (
"customlogger"
"fmt"
"net/http"
)
func main() {
logger := customlogger.GetInstance()
logger.Println("Starting")
http.HandleFunc("/", sroot)
http.ListenAndServe(":8080", nil)
}
func sroot(w http.ResponseWriter, r *http.Request) {
logger := customlogger.GetInstance()
fmt.Fprintf(w, "welcome")
logger.Println("Starting")
}