refactor: 使用nlog代替内置log接口,更换包名。

main v0.3.0
NoahLan 2 years ago
parent 3730205022
commit 5a9cbde34b

@ -3,11 +3,11 @@ package core
import (
"errors"
"fmt"
"git.noahlan.cn/northlan/nnet/internal/pool"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
"git.noahlan.cn/northlan/nnet/scheduler"
"git.noahlan.cn/northlan/nnet/session"
"git.noahlan.cn/noahlan/nnet/internal/pool"
"git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/scheduler"
"git.noahlan.cn/noahlan/nnet/session"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"net"
"sync/atomic"
"time"
@ -153,7 +153,7 @@ func (r *Connection) write() {
close(r.chWrite)
_ = r.Close()
log.Debugf("Connection write goroutine exit, ConnID=%d, SessionUID=%s", r.ID(), r.session.UID())
nlog.Debugf("Connection write goroutine exit, ConnID=%d, SessionUID=%s", r.ID(), r.session.UID())
}()
for {
@ -162,7 +162,7 @@ func (r *Connection) write() {
// TODO heartbeat enable control
deadline := time.Now().Add(-2 * r.ngin.heartbeatInterval).Unix()
if atomic.LoadInt64(&r.lastHeartbeatAt) < deadline {
log.Debugf("Session heartbeat timeout, LastTime=%d, Deadline=%d", atomic.LoadInt64(&r.lastHeartbeatAt), deadline)
nlog.Debugf("Session heartbeat timeout, LastTime=%d, Deadline=%d", atomic.LoadInt64(&r.lastHeartbeatAt), deadline)
return
}
// TODO heartbeat data
@ -171,13 +171,13 @@ func (r *Connection) write() {
// marshal packet body (data)
if r.ngin.serializer == nil {
if _, ok := data.payload.([]byte); !ok {
log.Errorf("serializer is nil, but payload type not []byte")
nlog.Errorf("serializer is nil, but payload type not []byte")
break
}
} else {
payload, err := r.ngin.serializer.Marshal(data.payload)
if err != nil {
log.Errorf("message body marshal err: %v", err)
nlog.Errorf("message body marshal err: %v", err)
break
}
data.payload = payload
@ -187,7 +187,7 @@ func (r *Connection) write() {
if pipe := r.ngin.pipeline; pipe != nil {
err := pipe.Outbound().Process(r, data)
if err != nil {
log.Errorf("broken pipeline err: %s", err.Error())
nlog.Errorf("broken pipeline err: %s", err.Error())
break
}
}
@ -195,14 +195,14 @@ func (r *Connection) write() {
// packet pack data
p, err := r.packer.Pack(data.header, data.payload.([]byte))
if err != nil {
log.Error(err.Error())
nlog.Error(err.Error())
break
}
r.chWrite <- p
case data := <-r.chWrite:
// 回写数据
if _, err := r.conn.Write(data); err != nil {
log.Error(err.Error())
nlog.Error(err.Error())
return
}
case <-r.chDie: // connection close signal
@ -222,24 +222,24 @@ func (r *Connection) read() {
for {
n, err := r.conn.Read(buf)
if err != nil {
log.Errorf("Read message error: %s, session will be closed immediately", err.Error())
nlog.Errorf("Read message error: %s, session will be closed immediately", err.Error())
return
}
if r.packer == nil {
log.Errorf("unexpected error: packer is nil")
nlog.Errorf("unexpected error: packer is nil")
return
}
// warning: 为性能考虑复用slice处理数据buf传入后必须要copy再处理
packets, err := r.packer.Unpack(buf[:n])
if err != nil {
log.Error(err.Error())
nlog.Error(err.Error())
}
// packets 处理
for _, p := range packets {
if err := r.processPacket(p); err != nil {
log.Error(err.Error())
nlog.Error(err.Error())
continue
}
}
@ -275,7 +275,7 @@ func (r *Connection) Close() error {
}
r.SetStatus(StatusClosed)
log.Debugf("close connection, ID: %d", r.ID())
nlog.Debugf("close connection, ID: %d", r.ID())
select {
case <-r.chDie:

@ -2,13 +2,14 @@ package core
import (
"errors"
"git.noahlan.cn/northlan/nnet/internal/pool"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
"git.noahlan.cn/northlan/nnet/scheduler"
"git.noahlan.cn/northlan/nnet/serialize"
"git.noahlan.cn/northlan/nnet/session"
"git.noahlan.cn/noahlan/nnet/internal/pool"
"git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/scheduler"
"git.noahlan.cn/noahlan/nnet/serialize"
"git.noahlan.cn/noahlan/nnet/session"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"os"
@ -19,7 +20,7 @@ import (
)
func NotFound(conn *Connection, packet packet.IPacket) {
log.Error("handler not found")
nlog.Error("handler not found")
conn.SendBytes([]byte("handler not found"))
}
@ -131,12 +132,12 @@ func (ng *engine) serve(router Router) error {
select {
case <-ng.dieChan:
log.Info("Server will shutdown in a few seconds")
nlog.Info("Server will shutdown in a few seconds")
case s := <-sg:
log.Infof("Server got signal: %s", s)
nlog.Infof("Server got signal: %s", s)
}
log.Info("Server is stopping...")
nlog.Info("Server is stopping...")
ng.shutdown()
scheduler.Close()
@ -158,7 +159,7 @@ func (ng *engine) listenAndServe() {
}
// 监听成功,服务已启动
log.Infof("now listening %s on %s.", ng.conf.Protocol, ng.conf.Addr)
nlog.Infof("now listening %s on %s.", ng.conf.Protocol, ng.conf.Addr)
defer func() {
listener.Close()
ng.close()
@ -168,10 +169,10 @@ func (ng *engine) listenAndServe() {
conn, err := listener.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
log.Errorf("服务器网络错误 %+v", err)
nlog.Errorf("服务器网络错误 %+v", err)
return
}
log.Errorf("监听错误 %v", err)
nlog.Errorf("监听错误 %v", err)
continue
}
@ -179,7 +180,7 @@ func (ng *engine) listenAndServe() {
ng.handle(conn)
})
if err != nil {
log.Errorf("submit conn pool err: %ng", err.Error())
nlog.Errorf("submit conn pool err: %ng", err.Error())
continue
}
}
@ -208,7 +209,7 @@ 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 {
log.Errorf("Upgrade failure, URI=%ng, Error=%ng", r.RequestURI, err.Error())
nlog.Errorf("Upgrade failure, URI=%ng, Error=%ng", r.RequestURI, err.Error())
return
}
err = pool.SubmitConn(func() {
@ -223,7 +224,7 @@ func (ng *engine) setupWS() {
func (ng *engine) handleWS(conn *websocket.Conn) {
c, err := newWSConn(conn)
if err != nil {
log.Error(err)
nlog.Error(err)
return
}
ng.handle(c)

@ -2,8 +2,8 @@ package core
import (
"errors"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
)
type nNetRouter struct {
@ -20,13 +20,13 @@ func NewRouter() Router {
func (r *nNetRouter) Handle(conn *Connection, p packet.IPacket) {
pkg, ok := p.(*packet.Packet)
if !ok {
log.Error(packet.ErrWrongMessage)
nlog.Error(packet.ErrWrongMessage)
return
}
handler, ok := r.handlers[pkg.Header.Route]
if !ok {
if r.notFound == nil {
log.Error("message handler not found")
nlog.Error("message handler not found")
return
}
r.notFound.Handle(conn, p)

@ -1,6 +1,6 @@
package core
import "git.noahlan.cn/northlan/nnet/packet"
import "git.noahlan.cn/noahlan/nnet/packet"
type (
Processor interface {

@ -4,8 +4,8 @@ import (
"encoding/json"
"errors"
"fmt"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"time"
)
@ -43,10 +43,10 @@ func (n *NNetProcessor) Process(conn *Connection, p packet.IPacket) error {
}
conn.SetStatus(StatusPrepare)
log.Debugf("connection handshake Id=%d, Remote=%s", conn.ID(), conn.Conn().RemoteAddr())
nlog.Debugf("connection handshake Id=%d, Remote=%s", conn.ID(), conn.Conn().RemoteAddr())
case packet.HandshakeAck:
conn.SetStatus(StatusPending)
log.Debugf("receive handshake ACK Id=%d, Remote=%s", conn.ID(), conn.Conn().RemoteAddr())
nlog.Debugf("receive handshake ACK Id=%d, Remote=%s", conn.ID(), conn.Conn().RemoteAddr())
case packet.Heartbeat:
// Expected
case packet.Data:

@ -1,10 +1,10 @@
package core
import (
"git.noahlan.cn/northlan/nnet/internal/env"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
"git.noahlan.cn/northlan/nnet/serialize"
"git.noahlan.cn/noahlan/nnet/internal/env"
"git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/serialize"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"net/http"
"time"
)
@ -49,7 +49,7 @@ func (s *Server) AddRoute(r Route) {
// Graceful shutdown is enabled by default.
func (s *Server) Start() {
if err := s.ngin.serve(s.router); err != nil {
log.Error(err)
nlog.Error(err)
panic(err)
}
}
@ -125,12 +125,6 @@ func WithSerializer(s serialize.Serializer) RunOption {
}
}
func WithLogger(logger log.Logger) RunOption {
return func(_ *Server) {
log.SetLogger(logger)
}
}
// WithTimerPrecision 设置Timer精度
// 注精度需大于1ms, 并且不能在运行时更改
// 默认精度是 time.Second

@ -2,8 +2,8 @@ package core
import (
"fmt"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"testing"
"time"
)
@ -29,7 +29,7 @@ func TestServer(t *testing.T) {
fmt.Println(pkg)
p, ok := pkg.(*packet.Packet)
if !ok {
log.Error("wrong packet type")
nlog.Error("wrong packet type")
return
}

@ -1,6 +1,6 @@
package core
import "git.noahlan.cn/northlan/nnet/packet"
import "git.noahlan.cn/noahlan/nnet/packet"
type (
Handler interface {

@ -1,10 +1,23 @@
module git.noahlan.cn/northlan/nnet
module git.noahlan.cn/noahlan/nnet
go 1.19
go 1.20
require (
github.com/gorilla/websocket v1.5.0
github.com/panjf2000/ants/v2 v2.6.0
)
require google.golang.org/protobuf v1.28.1 // indirect
require google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8
require (
git.noahlan.cn/noahlan/ntools-go/core v1.1.1
github.com/fatih/color v1.15.0 // indirect
github.com/gofrs/uuid/v5 v5.0.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
go.opentelemetry.io/otel v1.14.0 // indirect
go.opentelemetry.io/otel/trace v1.14.0 // indirect
golang.org/x/crypto v0.7.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/text v0.8.0 // indirect
)

@ -1,14 +1,40 @@
git.noahlan.cn/noahlan/ntools-go/core v1.1.1 h1:icFPOTTpVYPa8NpNJteAwFBARPOuHE3695xZWNcAM2c=
git.noahlan.cn/noahlan/ntools-go/core v1.1.1/go.mod h1:UN8UVL5WoyMgqNcxKoAu0/J9d+1hH2Yco64MUtPdjFk=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M=
github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/panjf2000/ants/v2 v2.6.0 h1:xOSpw42m+BMiJ2I33we7h6fYzG4DAlpE1xyI7VS2gxU=
github.com/panjf2000/ants/v2 v2.6.0/go.mod h1:cU93usDlihJZ5CfRGNDYsiBYvoilLvBF5Qp/BT2GNRE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM=
go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU=
go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY=
go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M=
go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8 h1:KR8+MyP7/qOlV+8Af01LtjL04bu7on42eVsxT4EyBQk=
google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

@ -1,88 +0,0 @@
package log
import (
"log"
"os"
)
type Logger interface {
Debugf(format string, v ...interface{})
Debug(v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
}
func init() {
SetLogger(newInnerLogger())
}
var (
Debugf func(format string, v ...interface{})
Debug func(v ...interface{})
Info func(v ...interface{})
Infof func(format string, v ...interface{})
Error func(v ...interface{})
Errorf func(format string, v ...interface{})
Fatal func(v ...interface{})
Fatalf func(format string, v ...interface{})
)
func SetLogger(logger Logger) {
if logger == nil {
return
}
Debugf = logger.Debugf
Debug = logger.Debug
Info = logger.Info
Infof = logger.Infof
Error = logger.Error
Errorf = logger.Errorf
Fatal = logger.Fatal
Fatalf = logger.Fatalf
}
type innerLogger struct {
log *log.Logger
}
func newInnerLogger() Logger {
return &innerLogger{
log: log.New(os.Stderr, "[N-Net] ", log.LstdFlags|log.Lshortfile),
}
}
func (i *innerLogger) Debugf(format string, v ...interface{}) {
i.log.Printf(format+"\n", v...)
}
func (i *innerLogger) Debug(v ...interface{}) {
i.log.Println(v...)
}
func (i *innerLogger) Info(v ...interface{}) {
i.log.Println(v...)
}
func (i *innerLogger) Infof(format string, v ...interface{}) {
i.log.Printf(format+"\n", v...)
}
func (i *innerLogger) Error(v ...interface{}) {
i.log.Println(v...)
}
func (i *innerLogger) Errorf(format string, v ...interface{}) {
i.log.Printf(format+"\n", v...)
}
func (i *innerLogger) Fatal(v ...interface{}) {
i.log.Fatal(v...)
}
func (i *innerLogger) Fatalf(format string, v ...interface{}) {
i.log.Fatalf(format+"\n", v...)
}

@ -1,8 +1,8 @@
package scheduler
import (
"git.noahlan.cn/northlan/nnet/internal/env"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/noahlan/nnet/internal/env"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"runtime/debug"
"sync/atomic"
"time"
@ -33,7 +33,7 @@ var (
func try(f func()) {
defer func() {
if err := recover(); err != nil {
log.Infof("Handle message panic: %+v\n%s", err, debug.Stack())
nlog.Infof("Handle message panic: %+v\n%s", err, debug.Stack())
}
}()
f()
@ -70,7 +70,7 @@ func Close() {
}
close(chDie)
<-chExit
log.Info("Scheduler stopped")
nlog.Info("Scheduler stopped")
}
func PushTask(task Task) {

@ -1,7 +1,7 @@
package scheduler
import (
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
"math"
"runtime/debug"
"sync"
@ -70,7 +70,7 @@ func (t *Timer) Stop() {
func safeCall(_ int64, fn TimerFunc) {
defer func() {
if err := recover(); err != nil {
log.Infof("Handle timer panic: %+v\n%s", err, debug.Stack())
nlog.Infof("Handle timer panic: %+v\n%s", err, debug.Stack())
}
}()

@ -2,7 +2,7 @@ package json
import (
"encoding/json"
"git.noahlan.cn/northlan/nnet/serialize"
"git.noahlan.cn/noahlan/nnet/serialize"
)
type Serializer struct{}

@ -2,7 +2,7 @@ package protobuf
import (
"errors"
"git.noahlan.cn/northlan/nnet/serialize"
"git.noahlan.cn/noahlan/nnet/serialize"
"google.golang.org/protobuf/proto"
)

@ -1,7 +1,7 @@
package protobuf
import (
"git.noahlan.cn/northlan/nnet/serialize/protobuf/testdata"
"git.noahlan.cn/noahlan/nnet/serialize/protobuf/testdata"
"google.golang.org/protobuf/proto"
"testing"
)

Loading…
Cancel
Save