fix: 优化debug的暂时时机和显示风格

main v0.5.1
NoahLan 2 years ago
parent 7de6cee180
commit 621db20ab1

@ -37,3 +37,8 @@ type (
Mode string `json:",default=dev,options=[dev,test,prod]"`
}
)
// ShallLogDebug 是否应该打印 Debug 级别的日志,打印的首要条件是 nlog 的打印级别为 debug
func ShallLogDebug(mode string) bool {
return mode == DevMode || mode == TestMode
}

@ -141,7 +141,10 @@ func (r *connection) write() {
close(r.chWrite)
_ = r.Close()
nlog.Debugf("[writeLoop] connection write goroutine exit, ConnID=%d, SessionUID=%s", r.ID(), r.session.UID())
if r.ngin.shallLogDebug() {
nlog.Debugf("%s [writeLoop] connection write goroutine exit, ConnID=%d, SessionUID=%s",
r.ngin.logPrefix(), r.ID(), r.session.UID())
}
}()
for {
@ -150,13 +153,13 @@ func (r *connection) write() {
// marshal packet body (data)
if r.ngin.serializer == nil {
if _, ok := data.payload.([]byte); !ok {
nlog.Errorf("serializer is nil, but payload type not []byte")
nlog.Errorf("%s serializer is nil, but payload type not []byte", r.ngin.logPrefix())
break
}
} else {
payload, err := r.ngin.serializer.Marshal(data.payload)
if err != nil {
nlog.Errorf("message body marshal err: %v", err)
nlog.Errorf("%s message body marshal err: %v", r.ngin.logPrefix(), err)
break
}
data.payload = payload
@ -166,21 +169,21 @@ func (r *connection) write() {
if pipe := r.ngin.pipeline; pipe != nil {
err := pipe.Outbound().Process(r, data)
if err != nil {
nlog.Errorf("pipeline err: %s", err.Error())
nlog.Errorf("%s pipeline err: %s", r.ngin.logPrefix(), err.Error())
}
}
// packet pack data
p, err := r.packer.Pack(data.header, data.payload.([]byte))
if err != nil {
nlog.Error(err.Error())
nlog.Errorf("%s pack err: %s", r.ngin.logPrefix(), err.Error())
break
}
r.chWrite <- p
case data := <-r.chWrite:
// 回写数据
if _, err := r.conn.Write(data); err != nil {
nlog.Error(err.Error())
nlog.Errorf("%s write data err: %s", r.ngin.logPrefix(), err.Error())
break
}
//nlog.Debugf("write data %v", data)
@ -202,24 +205,25 @@ func (r *connection) read() {
n, err := r.conn.Read(buf)
//nlog.Debugf("receive data %v", buf[:n])
if err != nil {
nlog.Errorf("[readLoop] Read message error: %s, session will be closed immediately", err.Error())
nlog.Errorf("%s [readLoop] Read message error: %s, session will be closed immediately",
r.ngin.logPrefix(), err.Error())
return
}
if r.packer == nil {
nlog.Errorf("[readLoop] unexpected error: packer is nil")
nlog.Errorf("%s [readLoop] unexpected error: packer is nil", r.ngin.logPrefix())
return
}
// warning: 为性能考虑复用slice处理数据buf传入后必须要copy再处理
packets, err := r.packer.Unpack(buf[:n])
if err != nil {
nlog.Error(err.Error())
nlog.Errorf("%s unpack err: %s", r.ngin.logPrefix(), err.Error())
}
// packets 处理
for _, p := range packets {
if err := r.processPacket(p); err != nil {
nlog.Error(err.Error())
nlog.Errorf("%s process packet err: %s", r.ngin.logPrefix(), err.Error())
continue
}
}
@ -249,7 +253,9 @@ func (r *connection) Close() error {
}
r.SetStatus(StatusClosed)
nlog.Debugf("close connection, ID: %d", r.ID())
if r.ngin.shallLogDebug() {
nlog.Debugf("%s close connection, ID: %d", r.ngin.logPrefix(), r.ID())
}
select {
case <-r.chDie:

@ -2,6 +2,7 @@ package core
import (
"errors"
"fmt"
"git.noahlan.cn/noahlan/nnet/config"
conn2 "git.noahlan.cn/noahlan/nnet/conn"
"git.noahlan.cn/noahlan/nnet/entity"
@ -15,10 +16,7 @@ import (
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
@ -35,6 +33,8 @@ type (
// engine TCP-engine
engine struct {
conf config.EngineConf // conf 配置
taskTimerPrecision time.Duration
middlewares []Middleware // 中间件
routes []Route // 路由
// handler 消息处理器
@ -49,7 +49,6 @@ type (
wsOpt wsOptions // websocket
taskTimerPrecision time.Duration
connManager *conn2.Manager
}
@ -72,12 +71,19 @@ func newEngine(conf config.EngineConf) *engine {
taskTimerPrecision: conf.TaskTimerPrecision,
connManager: conn2.NewManager(),
}
pool.InitPool(conf.Pool)
return s
}
func (ng *engine) shallLogDebug() bool {
return config.ShallLogDebug(ng.conf.Mode)
}
func (ng *engine) logPrefix() string {
return fmt.Sprintf("[NNet-%s]", ng.conf.Name)
}
func (ng *engine) use(middleware ...Middleware) {
ng.middlewares = append(ng.middlewares, middleware...)
}
@ -132,7 +138,9 @@ func (ng *engine) dial(addr string, router Router) (entity.NetworkEntity, error)
nlog.Must(err)
// 连接成功,客户端已启动
nlog.Infof("now connect to %s.", addr)
if ng.shallLogDebug() {
nlog.Debugf("now connect to %s.", addr)
}
return c, nil
}
@ -145,7 +153,7 @@ func (ng *engine) serve(router Router) error {
}
go scheduler.Schedule(ng.taskTimerPrecision)
defer func() {
nlog.Info("NNet is stopping...")
nlog.Infof("%s is stopping...", ng.logPrefix())
ng.shutdown()
scheduler.Close()
@ -161,16 +169,6 @@ func (ng *engine) serve(router Router) error {
ng.listenAndServe()
}
sg := make(chan os.Signal)
signal.Notify(sg, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTERM)
select {
case <-ng.dieChan:
nlog.Info("NNet will shutdown in a few seconds")
case s := <-sg:
nlog.Infof("NNet got signal: %s", s)
}
return nil
}
@ -186,7 +184,9 @@ func (ng *engine) listenAndServe() {
nlog.Must(err)
// 监听成功,服务已启动
nlog.Infof("now listening %s on %s.", ng.conf.Protocol, ng.conf.Addr)
if ng.shallLogDebug() {
nlog.Debugf("%s now listening %s at %s.", ng.logPrefix(), ng.conf.Protocol, ng.conf.Addr)
}
defer func() {
_ = listener.Close()
ng.close()
@ -196,10 +196,10 @@ func (ng *engine) listenAndServe() {
conn, err := listener.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
nlog.Errorf("服务器网络错误 %+v", err)
nlog.Errorf("%s 服务器网络错误 %+v", ng.logPrefix(), err)
return
}
nlog.Errorf("监听错误 %v", err)
nlog.Errorf("%s 监听错误 %v", ng.logPrefix(), err)
continue
}
@ -207,7 +207,7 @@ func (ng *engine) listenAndServe() {
ng.handle(conn)
})
if err != nil {
nlog.Errorf("submit conn pool err: %ng", err.Error())
nlog.Errorf("%s submit conn pool err: %ng", ng.logPrefix(), err.Error())
continue
}
}
@ -215,6 +215,9 @@ func (ng *engine) listenAndServe() {
func (ng *engine) listenAndServeWS() {
ng.setupWS()
if ng.shallLogDebug() {
nlog.Debugf("%s now listening websocket at %s.", ng.logPrefix(), ng.conf.Addr)
}
if err := http.ListenAndServe(ng.conf.Addr, nil); err != nil {
log.Fatal(err.Error())
}
@ -222,6 +225,9 @@ func (ng *engine) listenAndServeWS() {
func (ng *engine) listenAndServeWSTLS() {
ng.setupWS()
if ng.shallLogDebug() {
nlog.Debugf("%s now listening websocket with tls at %s.", ng.logPrefix(), ng.conf.Addr)
}
if err := http.ListenAndServeTLS(ng.conf.Addr, ng.wsOpt.TLSCertificate, ng.wsOpt.TLSKey, nil); err != nil {
log.Fatal(err.Error())
}
@ -236,14 +242,14 @@ func (ng *engine) setupWS() {
http.HandleFunc("/"+strings.TrimPrefix(ng.wsOpt.WebsocketPath, "/"), func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrade.Upgrade(w, r, nil)
if err != nil {
nlog.Errorf("Upgrade failure, URI=%ng, Error=%ng", r.RequestURI, err.Error())
nlog.Errorf("%s Upgrade failure, URI=%ng, Error=%ng", ng.logPrefix(), r.RequestURI, err.Error())
return
}
err = pool.Submit(func() {
ng.handleWS(conn)
})
if err != nil {
log.Fatalf("submit conn pool err: %ng", err.Error())
log.Fatalf("%s submit conn pool err: %v", ng.logPrefix(), err.Error())
}
})
}

Loading…
Cancel
Save