diff --git a/gorush/config.go b/gorush/config.go index 851f9d0..087a7ff 100644 --- a/gorush/config.go +++ b/gorush/config.go @@ -41,6 +41,7 @@ type SectionIos struct { } type SectionLog struct { + Format string `yaml:"format"` AccessLog string `yaml:"access_log"` AccessLevel string `yaml:"access_level"` ErrorLog string `yaml:"error_log"` @@ -73,6 +74,7 @@ func BuildDefaultPushConf() ConfYaml { conf.Ios.Production = false // log + conf.Log.Format = "string" conf.Log.AccessLog = "stdout" conf.Log.AccessLevel = "debug" conf.Log.ErrorLog = "stderr" diff --git a/gorush/log.go b/gorush/log.go index 41157fd..9b731cc 100644 --- a/gorush/log.go +++ b/gorush/log.go @@ -1,11 +1,34 @@ package gopush import ( + "encoding/json" "errors" + "fmt" "github.com/Sirupsen/logrus" + "github.com/gin-gonic/gin" "os" ) +var ( + green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109}) + white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109}) + yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109}) + red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109}) + blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109}) + magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109}) + cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109}) + reset = string([]byte{27, 91, 48, 109}) +) + +type LogReq struct { + Time string `json:"time"` + URI string `json:"uri"` + Method string `json:"method"` + IP string `json:"ip"` + ContentType string `json:"content_type"` + Agent string `json:"agent"` +} + func InitLog() error { var err error @@ -74,3 +97,37 @@ func SetLogLevel(log *logrus.Logger, levelString string) error { return nil } + +func LogRequest(uri, method, ip string, contentType string, agent string) { + var output string + log := &LogReq{ + URI: uri, + Method: method, + IP: ip, + ContentType: contentType, + Agent: agent, + } + + if PushConf.Log.Format == "json" { + logJson, err := json.Marshal(log) + + if err != nil { + LogError.Error("Marshaling JSON error") + return + } + + output = string(logJson) + } else { + // format is string + output = fmt.Sprintf("|%s header %s| %s %s %s %s %s", magenta, reset, log.Method, log.URI, log.IP, log.ContentType, log.Agent) + } + + LogAccess.Info(output) +} + +func LogMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + LogRequest(c.Request.URL.Path, c.Request.Method, c.ClientIP(), c.ContentType(), c.Request.Header.Get("User-Agent")) + c.Next() + } +} diff --git a/gorush/server.go b/gorush/server.go index e325cf9..af95c2a 100644 --- a/gorush/server.go +++ b/gorush/server.go @@ -48,6 +48,7 @@ func GetMainEngine() *gin.Engine { r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(VersionMiddleware()) + r.Use(LogMiddleware()) r.GET(PushConf.Api.StatGoUri, api.StatusHandler) r.POST(PushConf.Api.PushUri, pushHandler)