databag/net/server/internal/logger.go

62 lines
1.2 KiB
Go
Raw Normal View History

2022-01-11 06:20:32 +00:00
package databag
import (
"log"
"net/http"
"time"
2022-01-16 07:25:43 +00:00
"os"
"runtime"
"strings"
2022-01-17 05:11:24 +00:00
"github.com/kr/pretty"
2022-01-11 06:20:32 +00:00
)
2022-01-17 21:27:48 +00:00
var hideLog bool = false
2022-01-19 23:03:06 +00:00
func SetHideLog(hide bool) {
hideLog = hide
}
2022-01-17 21:27:48 +00:00
2022-01-11 06:20:32 +00:00
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s %s %s %s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}
2022-01-16 07:25:43 +00:00
2022-01-19 19:36:53 +00:00
func ErrResponse(w http.ResponseWriter, code int, err error) {
2022-01-19 20:07:57 +00:00
if !hideLog && err != nil {
_, file, line, _ := runtime.Caller(1)
p, _ := os.Getwd()
log.Printf("%s:%d %s", strings.TrimPrefix(file, p), line, err.Error())
}
2022-01-19 19:36:53 +00:00
w.WriteHeader(code)
}
func ErrMsg(err error) {
if !hideLog && err != nil {
_, file, line, _ := runtime.Caller(1)
p, _ := os.Getwd()
log.Printf("%s:%d %s", strings.TrimPrefix(file, p), line, err.Error())
}
}
2022-01-16 07:25:43 +00:00
func LogMsg(msg string) {
2022-01-17 21:27:48 +00:00
if !hideLog {
_, file, line, _ := runtime.Caller(1)
p, _ := os.Getwd()
log.Printf("%s:%d %s", strings.TrimPrefix(file, p), line, msg)
}
2022-01-16 07:25:43 +00:00
}
2022-01-17 05:11:24 +00:00
func PrintMsg(obj interface{}) {
pretty.Println(obj);
}