Browse Source

remove gin log

pull/123/head
yedf2 4 years ago
parent
commit
048abd90e2
  1. 2
      app/main.go
  2. 1
      common/config.go
  3. 12
      common/utils.go
  4. 2
      conf.sample.yml
  5. 13
      dtmcli/logger/log.go
  6. 2
      dtmcli/logger/logger_test.go
  7. 6
      dtmsvr/svr.go

2
app/main.go

@ -50,7 +50,7 @@ func main() {
fmt.Printf("version: %s commit: %s built at: %s\n", Version, Commit, Date) fmt.Printf("version: %s commit: %s built at: %s\n", Version, Commit, Date)
return return
} }
logger.Debugf("starting dtm....") logger.Infof("starting dtm....")
common.MustLoadConfig() common.MustLoadConfig()
if common.Config.ExamplesDB.Driver != "" { if common.Config.ExamplesDB.Driver != "" {
dtmcli.SetCurrentDBType(common.Config.ExamplesDB.Driver) dtmcli.SetCurrentDBType(common.Config.ExamplesDB.Driver)

1
common/config.go

@ -61,6 +61,7 @@ type configType struct {
GrpcPort int64 `yaml:"GrpcPort" default:"36790"` GrpcPort int64 `yaml:"GrpcPort" default:"36790"`
MicroService MicroService `yaml:"MicroService"` MicroService MicroService `yaml:"MicroService"`
UpdateBranchSync int64 `yaml:"UpdateBranchSync"` UpdateBranchSync int64 `yaml:"UpdateBranchSync"`
LogLevel string `yaml:"LogLevel" default:"info"`
ExamplesDB dtmcli.DBConf `yaml:"ExamplesDB"` ExamplesDB dtmcli.DBConf `yaml:"ExamplesDB"`
} }

12
common/utils.go

@ -26,7 +26,8 @@ import (
// GetGinApp init and return gin // GetGinApp init and return gin
func GetGinApp() *gin.Engine { func GetGinApp() *gin.Engine {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
app := gin.Default() app := gin.New()
app.Use(gin.Recovery())
app.Use(func(c *gin.Context) { app.Use(func(c *gin.Context) {
body := "" body := ""
if c.Request.Body != nil { if c.Request.Body != nil {
@ -37,11 +38,8 @@ func GetGinApp() *gin.Engine {
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rb)) c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rb))
} }
} }
began := time.Now()
logger.Debugf("begin %s %s query: %s body: %s", c.Request.Method, c.FullPath(), c.Request.URL.RawQuery, body) logger.Debugf("begin %s %s query: %s body: %s", c.Request.Method, c.FullPath(), c.Request.URL.RawQuery, body)
c.Next() c.Next()
logger.Debugf("used %d ms %s %s query: %s body: %s", time.Since(began).Milliseconds(), c.Request.Method, c.FullPath(), c.Request.URL.RawQuery, body)
}) })
app.Any("/api/ping", func(c *gin.Context) { c.JSON(200, map[string]interface{}{"msg": "pong"}) }) app.Any("/api/ping", func(c *gin.Context) { c.JSON(200, map[string]interface{}{"msg": "pong"}) })
return app return app
@ -50,6 +48,7 @@ func GetGinApp() *gin.Engine {
// WrapHandler name is clear // WrapHandler name is clear
func WrapHandler(fn func(*gin.Context) (interface{}, error)) gin.HandlerFunc { func WrapHandler(fn func(*gin.Context) (interface{}, error)) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
began := time.Now()
r, err := func() (r interface{}, rerr error) { r, err := func() (r interface{}, rerr error) {
defer dtmimp.P2E(&rerr) defer dtmimp.P2E(&rerr)
return fn(c) return fn(c)
@ -60,11 +59,12 @@ func WrapHandler(fn func(*gin.Context) (interface{}, error)) gin.HandlerFunc {
} else if err == nil { } else if err == nil {
b, err = json.Marshal(r) b, err = json.Marshal(r)
} }
if err != nil { if err != nil {
logger.Debugf("status: 500, code: 500 message: %s", err.Error()) logger.Errorf("%2dms 500 %s %s %s %s", time.Since(began).Milliseconds(), err.Error(), c.Request.Method, c.Request.RequestURI, string(b))
c.JSON(500, map[string]interface{}{"code": 500, "message": err.Error()}) c.JSON(500, map[string]interface{}{"code": 500, "message": err.Error()})
} else { } else {
logger.Debugf("status: 200, content: %s", string(b)) logger.Infof("%2dms 200 %s %s %s", time.Since(began).Milliseconds(), c.Request.Method, c.Request.RequestURI, string(b))
c.Status(200) c.Status(200)
c.Writer.Header().Add("Content-Type", "application/json") c.Writer.Header().Add("Content-Type", "application/json")
_, err = c.Writer.Write(b) _, err = c.Writer.Write(b)

2
conf.sample.yml

@ -39,6 +39,8 @@ Store: # specify which engine to store trans status
# TimeoutToFail: 35 # timeout for XA, TCC to fail. saga's timeout default to infinite, which can be overwritten in saga options # TimeoutToFail: 35 # timeout for XA, TCC to fail. saga's timeout default to infinite, which can be overwritten in saga options
# RetryInterval: 10 # the subtrans branch will be retried after this interval # RetryInterval: 10 # the subtrans branch will be retried after this interval
# LogLevel: 'info' # default: info. can be debug|info|warn|error
### dtm can run examples, and examples will use following config to connect db ### dtm can run examples, and examples will use following config to connect db
ExamplesDB: ExamplesDB:
Driver: 'mysql' Driver: 'mysql'

13
dtmcli/logger/log.go

@ -11,21 +11,22 @@ import (
var logger *zap.SugaredLogger = nil var logger *zap.SugaredLogger = nil
func init() { func init() {
InitLog() InitLog("info")
} }
// InitLog is a initialization for a logger // InitLog is a initialization for a logger
func InitLog() { // level can be: debug info warn error
func InitLog(level string) {
config := zap.NewProductionConfig() config := zap.NewProductionConfig()
err := config.Level.UnmarshalText([]byte(level))
FatalIfError(err)
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
if os.Getenv("DTM_DEBUG") != "" { if os.Getenv("DTM_DEBUG") != "" {
config.Encoding = "console" config.Encoding = "console"
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
} }
p, err := config.Build(zap.AddCallerSkip(1)) p, err := config.Build(zap.AddCallerSkip(1))
if err != nil { FatalIfError(err)
log.Fatal("create logger failed: ", err)
}
logger = p.Sugar() logger = p.Sugar()
} }
@ -54,7 +55,7 @@ func FatalfIf(cond bool, fmt string, args ...interface{}) {
if !cond { if !cond {
return return
} }
logger.Fatalf(fmt, args...) log.Fatalf(fmt, args...)
} }
// FatalIfError if err is not nil, then log to level fatal and call os.Exit // FatalIfError if err is not nil, then log to level fatal and call os.Exit

2
dtmcli/logger/logger_test.go

@ -7,7 +7,7 @@ import (
func TestInitLog(t *testing.T) { func TestInitLog(t *testing.T) {
os.Setenv("DTM_DEBUG", "1") os.Setenv("DTM_DEBUG", "1")
InitLog() InitLog("debug")
Debugf("a debug msg") Debugf("a debug msg")
Infof("a info msg") Infof("a info msg")
Warnf("a warn msg") Warnf("a warn msg")

6
dtmsvr/svr.go

@ -22,11 +22,11 @@ import (
// StartSvr StartSvr // StartSvr StartSvr
func StartSvr() { func StartSvr() {
logger.Debugf("start dtmsvr") logger.Infof("start dtmsvr")
app := common.GetGinApp() app := common.GetGinApp()
app = httpMetrics(app) app = httpMetrics(app)
addRoute(app) addRoute(app)
logger.Debugf("dtmsvr listen at: %d", config.HttpPort) logger.Infof("dtmsvr listen at: %d", config.HttpPort)
go app.Run(fmt.Sprintf(":%d", config.HttpPort)) go app.Run(fmt.Sprintf(":%d", config.HttpPort))
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", config.GrpcPort)) lis, err := net.Listen("tcp", fmt.Sprintf(":%d", config.GrpcPort))
@ -36,7 +36,7 @@ func StartSvr() {
grpc.UnaryServerInterceptor(grpcMetrics), grpc.UnaryServerInterceptor(dtmgimp.GrpcServerLog)), grpc.UnaryServerInterceptor(grpcMetrics), grpc.UnaryServerInterceptor(dtmgimp.GrpcServerLog)),
)) ))
dtmgpb.RegisterDtmServer(s, &dtmServer{}) dtmgpb.RegisterDtmServer(s, &dtmServer{})
logger.Debugf("grpc listening at %v", lis.Addr()) logger.Infof("grpc listening at %v", lis.Addr())
go func() { go func() {
err := s.Serve(lis) err := s.Serve(lis)
logger.FatalIfError(err) logger.FatalIfError(err)

Loading…
Cancel
Save