diff --git a/examples/ding-dong-bot.go b/examples/ding-dong-bot.go index 0135061..509ec58 100644 --- a/examples/ding-dong-bot.go +++ b/examples/ding-dong-bot.go @@ -80,11 +80,11 @@ func onMessage(ctx *wechaty.Context, message *user.Message) { log.Printf("REPLY with urlLink: %s\n", urlLink) } -func onScan(ctx *wechaty.Context, qrCode string, status schemas.ScanStatus, data string) { +func onScan(ctx *wechaty.Context, qrCode string, status schemas.ScanStatus, data string) { if status == schemas.ScanStatusWaiting || status == schemas.ScanStatusTimeout { qrterminal.GenerateHalfBlock(qrCode, qrterminal.L, os.Stdout) - qrcodeImageUrl := fmt.Sprintf("https://wechaty.js.org/qrcode/%s",url.QueryEscape(qrCode)) + qrcodeImageUrl := fmt.Sprintf("https://wechaty.js.org/qrcode/%s", url.QueryEscape(qrCode)) fmt.Printf("onScan: %s - %s\n", status, qrcodeImageUrl) return } diff --git a/go.mod b/go.mod index 2bd0d75..cf5534f 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/lucsky/cuid v1.0.2 github.com/mdp/qrterminal/v3 v3.0.0 github.com/otiai10/opengraph v1.1.1 + github.com/sirupsen/logrus v1.9.0 github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086 github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 github.com/wechaty/go-grpc v1.5.2 @@ -19,9 +20,10 @@ require ( github.com/google/uuid v1.1.2 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.0 // indirect github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 // indirect + github.com/stretchr/testify v1.8.0 // indirect github.com/willf/bitset v1.1.10 // indirect golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect - golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect + golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect golang.org/x/text v0.3.7 // indirect google.golang.org/genproto v0.0.0-20220317150908-0efb43f6373e // indirect rsc.io/qr v0.2.0 // indirect diff --git a/go.sum b/go.sum index 9c48b7c..ef347cb 100644 --- a/go.sum +++ b/go.sum @@ -13,6 +13,8 @@ github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -67,16 +69,23 @@ github.com/otiai10/mint v1.3.0 h1:Ady6MKVezQwHBkGzLFbrsywyp09Ah7rkmfjV3Bcr5uc= github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= github.com/otiai10/opengraph v1.1.1 h1:zaHbzhegXGqxVpiI7xlQQ0vKBWvHJbagnUjDC40sFtQ= github.com/otiai10/opengraph v1.1.1/go.mod h1:ZMbPcfiSRSsg3+yrWZCXrgYL6kEK4KpH4GG1iyIvEXs= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086 h1:RYiqpb2ii2Z6J4x0wxK46kvPBbFuZcdhS+CIztmYgZs= github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086/go.mod h1:PLPIyL7ikehBD1OAjmKKiOEhbvWyHGaNDjquXMcYABo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 h1:BWVtt2VBY+lmVDu9MGKqLGKl04B+iRHcrW1Ptyi/8tg= github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2/go.mod h1:lPnW9HVS0vJdeYyQtOvIvlXgZPNhUAhwz+z5r8AJk0Y= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= @@ -116,8 +125,8 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -166,6 +175,8 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY= diff --git a/wechaty-puppet-service/config.go b/wechaty-puppet-service/config.go index a0b7ab8..68418dc 100644 --- a/wechaty-puppet-service/config.go +++ b/wechaty-puppet-service/config.go @@ -1,6 +1,9 @@ package puppetservice -import "os" +import ( + logger "github.com/wechaty/go-wechaty/wechaty-puppet/log" + "os" +) var ( // WechatyPuppetHostieToken ... @@ -18,6 +21,8 @@ var ( WechatyPuppetServiceEndpoint string ) +var log = logger.L.WithField("module", "wechaty-puppet-service") + func init() { WechatyPuppetHostieToken, _ = os.LookupEnv("WECHATY_PUPPET_HOSTIE_TOKEN") WechatyPuppetHostieEndpoint, _ = os.LookupEnv("WECHATY_PUPPET_HOSTIE_ENDPOINT") diff --git a/wechaty-puppet-service/puppet_service.go b/wechaty-puppet-service/puppet_service.go index 8e31139..3bae64f 100644 --- a/wechaty-puppet-service/puppet_service.go +++ b/wechaty-puppet-service/puppet_service.go @@ -16,7 +16,6 @@ import ( "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/timestamppb" "io" - "log" "time" ) @@ -68,7 +67,7 @@ func getPuppetServiceTokenFromEnv() string { return WechatyPuppetServiceToken } if WechatyPuppetHostieToken != "" { - log.Println(`warn: WECHATY_PUPPET_HOSTIE_TOKEN environment be deprecated + log.Warn(`warn: WECHATY_PUPPET_HOSTIE_TOKEN environment be deprecated please use new environment name to avoid unnecessary bugs`) return WechatyPuppetHostieToken } @@ -80,7 +79,7 @@ func getPuppetServiceEndpointFromEnv() string { return WechatyPuppetServiceEndpoint } if WechatyPuppetServiceEndpoint != "" { - log.Println(`warn: WECHATY_PUPPET_HOSTIE_ENDPOINT environment be deprecated + log.Warn(`warn: WECHATY_PUPPET_HOSTIE_ENDPOINT environment be deprecated please use new environment name to avoid unnecessary bugs`) return WechatyPuppetServiceEndpoint } @@ -89,7 +88,7 @@ please use new environment name to avoid unnece // MessageImage ... func (p *PuppetService) MessageImage(messageID string, imageType schemas.ImageType) (*filebox.FileBox, error) { - log.Printf("PuppetService MessageImage(%s, %s)\n", messageID, imageType) + log.Tracef("PuppetService MessageImage(%s, %s)\n", messageID, imageType) response, err := p.grpcClient.MessageImage(context.Background(), &pbwechatypuppet.MessageImageRequest{ Id: messageID, Type: pbwechatypuppet.ImageType(imageType), @@ -102,7 +101,7 @@ func (p *PuppetService) MessageImage(messageID string, imageType schemas.ImageTy // Start ... func (p *PuppetService) Start() (err error) { - log.Println("PuppetService Start()") + log.Tracef("PuppetService Start()") defer func() { if err != nil { err = fmt.Errorf("PuppetService Start() rejection: %w", err) @@ -172,7 +171,7 @@ func (p *PuppetService) Stop() { var err error defer func() { if err != nil { - log.Printf("PuppetService Stop err: %s\n", err) + log.Errorf("PuppetService Stop err: %s\n", err) } }() if p.logonoff() { @@ -209,14 +208,14 @@ func (p *PuppetService) stopGrpcClient() error { } func (p *PuppetService) stopGrpcStream() error { - log.Println("PuppetService stopGrpcStream()") + log.Trace("PuppetService stopGrpcStream()") if p.eventStream == nil { return errors.New("no event stream") } if err := p.eventStream.CloseSend(); err != nil { - log.Printf("PuppetService stopGrpcStream() err: %s\n", err) + log.Tracef("PuppetService stopGrpcStream() err: %s\n", err) } p.eventStream = nil return nil @@ -266,16 +265,16 @@ func (p *PuppetService) autoReconnectGrpcConn() { // 重新连接成功 if isClose && connectivity.Ready == connState { isClose = false - log.Printf("PuppetService.autoReconnectGrpcConn grpc reconnection successful") + log.Info("PuppetService.autoReconnectGrpcConn grpc reconnection successful") if err := p.startGrpcStream(); err != nil { - log.Printf("PuppetService.autoReconnectGrpcConn startGrpcStream err:%s", err.Error()) + log.Errorf("PuppetService.autoReconnectGrpcConn startGrpcStream err:%s", err.Error()) } } if p.grpcConn.GetState() == connectivity.Idle { isClose = true p.grpcConn.Connect() - log.Printf("PuppetService.autoReconnectGrpcConn grpc reconnection...") + log.Info("PuppetService.autoReconnectGrpcConn grpc reconnection...") } case <-p.stop: return @@ -301,11 +300,11 @@ func (p *PuppetService) startGrpcStream() (err error) { for { reply, err := p.eventStream.Recv() if err == io.EOF { - log.Println("eventStream.Recv EOF") + log.Error("eventStream.Recv EOF") break } if err != nil { - log.Printf("PuppetService startGrpcStream() eventStream err %s", err) + log.Errorf("PuppetService startGrpcStream() eventStream err %s", err) reason := "startGrpcStream() eventStream err: " + err.Error() p.Emit(schemas.PuppetEventNameReset, schemas.EventResetPayload{Data: reason}) p.eventStream = nil @@ -318,7 +317,7 @@ func (p *PuppetService) startGrpcStream() (err error) { } func (p *PuppetService) onGrpcStreamEvent(event *pbwechatypuppet.EventResponse) { - log.Printf("PuppetService onGrpcStreamEvent({type:%s payload:%s})", event.Type, event.Payload) + log.Tracef("PuppetService onGrpcStreamEvent({type:%s payload:%s})", event.Type, event.Payload) if event.Type != pbwechatypuppet.EventType_EVENT_TYPE_HEARTBEAT { p.Emit(schemas.PuppetEventNameHeartbeat, &schemas.EventHeartbeatPayload{ @@ -326,19 +325,19 @@ func (p *PuppetService) onGrpcStreamEvent(event *pbwechatypuppet.EventResponse) }) } if event.Type == pbwechatypuppet.EventType_EVENT_TYPE_UNSPECIFIED { - log.Println("PuppetService onGrpcStreamEvent() got an EventType.EVENT_TYPE_UNSPECIFIED ") + log.Warn("PuppetService onGrpcStreamEvent() got an EventType.EVENT_TYPE_UNSPECIFIED ") return } eventName, ok := pbEventType2PuppetEventName[event.Type] if !ok { - log.Printf("'eventType %s unsupported! (code should not reach here)\n", event.Type) + log.Warnf("'eventType %s unsupported! (code should not reach here)\n", event.Type) return } payload := pbEventType2GeneratePayloadFunc[event.Type]() p.unMarshal(event.Payload, payload) switch event.Type { case pbwechatypuppet.EventType_EVENT_TYPE_RESET: - log.Println("PuppetService onGrpcStreamEvent() got an EventType.EVENT_TYPE_RESET ?") + log.Warnf("PuppetService onGrpcStreamEvent() got an EventType.EVENT_TYPE_RESET ?") // the `reset` event should be dealed not send out return case pbwechatypuppet.EventType_EVENT_TYPE_LOGIN: @@ -352,13 +351,13 @@ func (p *PuppetService) onGrpcStreamEvent(event *pbwechatypuppet.EventResponse) func (p *PuppetService) unMarshal(data string, v interface{}) { err := json.Unmarshal([]byte(data), v) if err != nil { - log.Printf("PuppetService unMarshal err: %s\n", err) + log.Errorf("PuppetService unMarshal err: %s\n", err) } } // Logout ... func (p *PuppetService) Logout() error { - log.Println("PuppetService Logout()") + log.Tracef("PuppetService Logout()") if !p.logonoff() { return errors.New("logout before login? ") } @@ -375,18 +374,18 @@ func (p *PuppetService) Logout() error { // Ding ... func (p *PuppetService) Ding(data string) { - log.Printf("PuppetService Ding(%s)\n", data) + log.Tracef("PuppetService Ding(%s)\n", data) _, err := p.grpcClient.Ding(context.Background(), &pbwechatypuppet.DingRequest{ Data: data, }) if err != nil { - log.Printf("PuppetService Ding() err: %s\n", err) + log.Tracef("PuppetService Ding() err: %s\n", err) } } // SetContactAlias ... func (p *PuppetService) SetContactAlias(contactID string, alias string) error { - log.Printf("PuppetService, SetContactAlias(%s, %s)\n", contactID, alias) + log.Tracef("PuppetService, SetContactAlias(%s, %s)\n", contactID, alias) _, err := p.grpcClient.ContactAlias(context.Background(), &pbwechatypuppet.ContactAliasRequest{ Id: contactID, Alias: &alias, @@ -399,7 +398,7 @@ func (p *PuppetService) SetContactAlias(contactID string, alias string) error { // ContactAlias ... func (p *PuppetService) ContactAlias(contactID string) (string, error) { - log.Printf("PuppetService, 'ContactAlias(%s)\n", contactID) + log.Tracef("PuppetService, 'ContactAlias(%s)\n", contactID) response, err := p.grpcClient.ContactAlias(context.Background(), &pbwechatypuppet.ContactAliasRequest{ Id: contactID, }) @@ -411,7 +410,7 @@ func (p *PuppetService) ContactAlias(contactID string) (string, error) { // ContactList ... func (p *PuppetService) ContactList() ([]string, error) { - log.Println("PuppetService ContactList()") + log.Trace("PuppetService ContactList()") response, err := p.grpcClient.ContactList(context.Background(), &pbwechatypuppet.ContactListRequest{}) if err != nil { return nil, fmt.Errorf("PuppetService ContactList err: %w", err) @@ -421,7 +420,7 @@ func (p *PuppetService) ContactList() ([]string, error) { // ContactQRCode ... func (p *PuppetService) ContactQRCode(contactID string) (string, error) { - log.Printf("PuppetService ContactQRCode(%s)\n", contactID) + log.Tracef("PuppetService ContactQRCode(%s)\n", contactID) if contactID != p.SelfID() { return "", errors.New("can not set avatar for others") } @@ -434,7 +433,7 @@ func (p *PuppetService) ContactQRCode(contactID string) (string, error) { // SetContactAvatar ... func (p *PuppetService) SetContactAvatar(contactID string, fileBox *filebox.FileBox) error { - log.Printf("PuppetService SetContactAvatar(%s)\n", contactID) + log.Tracef("PuppetService SetContactAvatar(%s)\n", contactID) var err error fileBox, err = serializeFileBox(fileBox) @@ -457,7 +456,7 @@ func (p *PuppetService) SetContactAvatar(contactID string, fileBox *filebox.File // ContactAvatar ... func (p *PuppetService) ContactAvatar(contactID string) (*filebox.FileBox, error) { - log.Printf("PuppetService ContactAvatar(%s)\n", contactID) + log.Tracef("PuppetService ContactAvatar(%s)\n", contactID) response, err := p.grpcClient.ContactAvatar(context.Background(), &pbwechatypuppet.ContactAvatarRequest{ Id: contactID, }) @@ -469,7 +468,7 @@ func (p *PuppetService) ContactAvatar(contactID string) (*filebox.FileBox, error // ContactRawPayload ... func (p *PuppetService) ContactRawPayload(contactID string) (*schemas.ContactPayload, error) { - log.Printf("PuppetService ContactRawPayload(%s)\n", contactID) + log.Tracef("PuppetService ContactRawPayload(%s)\n", contactID) response, err := p.grpcClient.ContactPayload(context.Background(), &pbwechatypuppet.ContactPayloadRequest{ Id: contactID, }) @@ -495,7 +494,7 @@ func (p *PuppetService) ContactRawPayload(contactID string) (*schemas.ContactPay // SetContactSelfName ... func (p *PuppetService) SetContactSelfName(name string) error { - log.Printf("PuppetService SetContactSelfName(%s)\n", name) + log.Tracef("PuppetService SetContactSelfName(%s)\n", name) _, err := p.grpcClient.ContactSelfName(context.Background(), &pbwechatypuppet.ContactSelfNameRequest{ Name: name, }) @@ -504,7 +503,7 @@ func (p *PuppetService) SetContactSelfName(name string) error { // ContactSelfQRCode ... func (p *PuppetService) ContactSelfQRCode() (string, error) { - log.Println("PuppetService ContactSelfQRCode()") + log.Tracef("PuppetService ContactSelfQRCode()") response, err := p.grpcClient.ContactSelfQRCode(context.Background(), &pbwechatypuppet.ContactSelfQRCodeRequest{}) if err != nil { return "", err @@ -514,7 +513,7 @@ func (p *PuppetService) ContactSelfQRCode() (string, error) { // SetContactSelfSignature ... func (p *PuppetService) SetContactSelfSignature(signature string) error { - log.Printf("PuppetService SetContactSelfSignature(%s)\n", signature) + log.Tracef("PuppetService SetContactSelfSignature(%s)\n", signature) _, err := p.grpcClient.ContactSelfSignature(context.Background(), &pbwechatypuppet.ContactSelfSignatureRequest{ Signature: signature, }) @@ -523,7 +522,7 @@ func (p *PuppetService) SetContactSelfSignature(signature string) error { // MessageRawMiniProgramPayload ... func (p *PuppetService) MessageRawMiniProgramPayload(messageID string) (*schemas.MiniProgramPayload, error) { - log.Printf("PuppetService MessageMiniProgram(%s)\n", messageID) + log.Tracef("PuppetService MessageMiniProgram(%s)\n", messageID) response, err := p.grpcClient.MessageMiniProgram(context.Background(), &pbwechatypuppet.MessageMiniProgramRequest{ Id: messageID, }) @@ -555,7 +554,7 @@ func (p *PuppetService) MessageRawMiniProgramPayload(messageID string) (*schemas // MessageContact ... func (p *PuppetService) MessageContact(messageID string) (string, error) { - log.Printf("PuppetService MessageContact(%s)\n", messageID) + log.Tracef("PuppetService MessageContact(%s)\n", messageID) response, err := p.grpcClient.MessageContact(context.Background(), &pbwechatypuppet.MessageContactRequest{ Id: messageID, }) @@ -567,7 +566,7 @@ func (p *PuppetService) MessageContact(messageID string) (string, error) { // MessageSendMiniProgram ... func (p *PuppetService) MessageSendMiniProgram(conversationID string, miniProgramPayload *schemas.MiniProgramPayload) (string, error) { - log.Printf("PuppetService MessageSendMiniProgram(%s,%#v)\n", conversationID, miniProgramPayload) + log.Tracef("PuppetService MessageSendMiniProgram(%s,%#v)\n", conversationID, miniProgramPayload) response, err := p.grpcClient.MessageSendMiniProgram(context.Background(), &pbwechatypuppet.MessageSendMiniProgramRequest{ ConversationId: conversationID, MiniProgram: &pbwechatypuppet.MiniProgramPayload{ @@ -592,7 +591,7 @@ func (p *PuppetService) MessageSendMiniProgram(conversationID string, miniProgra // MessageRecall ... func (p *PuppetService) MessageRecall(messageID string) (bool, error) { - log.Printf("PuppetService MessageRecall(%s)\n", messageID) + log.Tracef("PuppetService MessageRecall(%s)\n", messageID) response, err := p.grpcClient.MessageRecall(context.Background(), &pbwechatypuppet.MessageRecallRequest{ Id: messageID, }) @@ -604,7 +603,7 @@ func (p *PuppetService) MessageRecall(messageID string) (bool, error) { // MessageFile ... func (p *PuppetService) MessageFile(id string) (*filebox.FileBox, error) { - log.Printf("PuppetService MessageFile(%s)\n", id) + log.Tracef("PuppetService MessageFile(%s)\n", id) response, err := p.grpcClient.MessageFileStream(context.Background(), &pbwechatypuppet.MessageFileStreamRequest{ Id: id, }) @@ -616,7 +615,7 @@ func (p *PuppetService) MessageFile(id string) (*filebox.FileBox, error) { // MessageRawPayload ... func (p *PuppetService) MessageRawPayload(id string) (*schemas.MessagePayload, error) { - log.Printf("PuppetService MessagePayload(%s)\n", id) + log.Tracef("PuppetService MessagePayload(%s)\n", id) response, err := p.grpcClient.MessagePayload(context.Background(), &pbwechatypuppet.MessagePayloadRequest{ Id: id, }) @@ -653,7 +652,7 @@ func grpcTimestampToGoTime(t *timestamppb.Timestamp) time.Time { // MessageSendText ... func (p *PuppetService) MessageSendText(conversationID string, text string, mentionIDList ...string) (string, error) { - log.Printf("PuppetService messageSendText(%s, %s)\n", conversationID, text) + log.Tracef("PuppetService messageSendText(%s, %s)\n", conversationID, text) response, err := p.grpcClient.MessageSendText(context.Background(), &pbwechatypuppet.MessageSendTextRequest{ ConversationId: conversationID, Text: text, @@ -667,7 +666,7 @@ func (p *PuppetService) MessageSendText(conversationID string, text string, ment // MessageSendFile ... func (p *PuppetService) MessageSendFile(conversationID string, fileBox *filebox.FileBox) (string, error) { - log.Printf("PuppetService MessageSendFile(%s)\n", conversationID) + log.Tracef("PuppetService MessageSendFile(%s)\n", conversationID) if msgID, err := p.messageSendFileNonStream(conversationID, fileBox); err == nil { return msgID, nil } @@ -723,7 +722,7 @@ var serializableFileBoxTypes = helper.ArrayInt{ } func (p *PuppetService) messageSendFileNonStream(conversationID string, fileBox *filebox.FileBox) (string, error) { - log.Printf("PuppetService MessageSendFile(%s)\n", conversationID) + log.Tracef("PuppetService MessageSendFile(%s)\n", conversationID) var err error jsonText := "" @@ -754,7 +753,7 @@ func (p *PuppetService) messageSendFileNonStream(conversationID string, fileBox // MessageSendContact ... func (p *PuppetService) MessageSendContact(conversationID string, contactID string) (string, error) { - log.Printf("PuppetService MessageSendContact(%s, %s)\n", conversationID, contactID) + log.Tracef("PuppetService MessageSendContact(%s, %s)\n", conversationID, contactID) response, err := p.grpcClient.MessageSendContact(context.Background(), &pbwechatypuppet.MessageSendContactRequest{ ConversationId: conversationID, ContactId: contactID, @@ -767,7 +766,7 @@ func (p *PuppetService) MessageSendContact(conversationID string, contactID stri // MessageSendURL ... func (p *PuppetService) MessageSendURL(conversationID string, urlLinkPayload *schemas.UrlLinkPayload) (string, error) { - log.Printf("PuppetService MessageSendURL(%s, %+v)\n", conversationID, urlLinkPayload) + log.Tracef("PuppetService MessageSendURL(%s, %+v)\n", conversationID, urlLinkPayload) response, err := p.grpcClient.MessageSendUrl(context.Background(), &pbwechatypuppet.MessageSendUrlRequest{ ConversationId: conversationID, UrlLink: &pbwechatypuppet.UrlLinkPayload{ @@ -788,7 +787,7 @@ func (p *PuppetService) MessageSendURL(conversationID string, urlLinkPayload *sc // MessageURL ... func (p *PuppetService) MessageURL(messageID string) (*schemas.UrlLinkPayload, error) { - log.Printf("PuppetService MessageURL(%s)\n", messageID) + log.Tracef("PuppetService MessageURL(%s)\n", messageID) response, err := p.grpcClient.MessageUrl(context.Background(), &pbwechatypuppet.MessageUrlRequest{ Id: messageID, }) @@ -814,7 +813,7 @@ func (p *PuppetService) MessageURL(messageID string) (*schemas.UrlLinkPayload, e // RoomRawPayload ... func (p *PuppetService) RoomRawPayload(id string) (*schemas.RoomPayload, error) { - log.Printf("PuppetService RoomRawPayload(%s)\n", id) + log.Tracef("PuppetService RoomRawPayload(%s)\n", id) response, err := p.grpcClient.RoomPayload(context.Background(), &pbwechatypuppet.RoomPayloadRequest{ Id: id, }) @@ -833,7 +832,7 @@ func (p *PuppetService) RoomRawPayload(id string) (*schemas.RoomPayload, error) // RoomList ... func (p *PuppetService) RoomList() ([]string, error) { - log.Printf("PuppetService RoomList()\n") + log.Tracef("PuppetService RoomList()\n") response, err := p.grpcClient.RoomList(context.Background(), &pbwechatypuppet.RoomListRequest{}) if err != nil { return nil, err @@ -843,7 +842,7 @@ func (p *PuppetService) RoomList() ([]string, error) { // RoomDel ... func (p *PuppetService) RoomDel(roomID, contactID string) error { - log.Printf("PuppetService roomDel(%s, %s)\n", roomID, contactID) + log.Tracef("PuppetService roomDel(%s, %s)\n", roomID, contactID) _, err := p.grpcClient.RoomDel(context.Background(), &pbwechatypuppet.RoomDelRequest{ Id: roomID, ContactId: contactID, @@ -856,7 +855,7 @@ func (p *PuppetService) RoomDel(roomID, contactID string) error { // RoomAvatar ... func (p *PuppetService) RoomAvatar(roomID string) (*filebox.FileBox, error) { - log.Printf("PuppetService RoomAvatar(%s)\n", roomID) + log.Tracef("PuppetService RoomAvatar(%s)\n", roomID) response, err := p.grpcClient.RoomAvatar(context.Background(), &pbwechatypuppet.RoomAvatarRequest{ Id: roomID, }) @@ -868,7 +867,7 @@ func (p *PuppetService) RoomAvatar(roomID string) (*filebox.FileBox, error) { // RoomAdd ... func (p *PuppetService) RoomAdd(roomID, contactID string) error { - log.Printf("PuppetService RoomAdd(%s, %s)\n", roomID, contactID) + log.Tracef("PuppetService RoomAdd(%s, %s)\n", roomID, contactID) _, err := p.grpcClient.RoomAdd(context.Background(), &pbwechatypuppet.RoomAddRequest{ Id: roomID, ContactId: contactID, @@ -881,7 +880,7 @@ func (p *PuppetService) RoomAdd(roomID, contactID string) error { // SetRoomTopic ... func (p *PuppetService) SetRoomTopic(roomID string, topic string) error { - log.Printf("PuppetService setRoomTopic(%s, %s)\n", roomID, topic) + log.Tracef("PuppetService setRoomTopic(%s, %s)\n", roomID, topic) _, err := p.grpcClient.RoomTopic(context.Background(), &pbwechatypuppet.RoomTopicRequest{ Id: roomID, Topic: &topic, @@ -891,7 +890,7 @@ func (p *PuppetService) SetRoomTopic(roomID string, topic string) error { // RoomTopic ... func (p *PuppetService) RoomTopic(roomID string) (string, error) { - log.Printf("PuppetService RoomTopic(%s)\n", roomID) + log.Tracef("PuppetService RoomTopic(%s)\n", roomID) response, err := p.grpcClient.RoomTopic(context.Background(), &pbwechatypuppet.RoomTopicRequest{ Id: roomID, }) @@ -903,7 +902,7 @@ func (p *PuppetService) RoomTopic(roomID string) (string, error) { // RoomCreate ... func (p *PuppetService) RoomCreate(contactIDList []string, topic string) (string, error) { - log.Printf("PuppetService roomCreate(%s, %s)\n", contactIDList, topic) + log.Tracef("PuppetService roomCreate(%s, %s)\n", contactIDList, topic) response, err := p.grpcClient.RoomCreate(context.Background(), &pbwechatypuppet.RoomCreateRequest{ ContactIds: contactIDList, Topic: topic, @@ -916,7 +915,7 @@ func (p *PuppetService) RoomCreate(contactIDList []string, topic string) (string // RoomQuit ... func (p *PuppetService) RoomQuit(roomID string) error { - log.Printf("PuppetService RoomQuit(%s)\n", roomID) + log.Tracef("PuppetService RoomQuit(%s)\n", roomID) _, err := p.grpcClient.RoomQuit(context.Background(), &pbwechatypuppet.RoomQuitRequest{ Id: roomID, }) @@ -928,7 +927,7 @@ func (p *PuppetService) RoomQuit(roomID string) error { // RoomQRCode ... func (p *PuppetService) RoomQRCode(roomID string) (string, error) { - log.Printf("PuppetService RoomQRCode(%s)\n", roomID) + log.Tracef("PuppetService RoomQRCode(%s)\n", roomID) response, err := p.grpcClient.RoomQRCode(context.Background(), &pbwechatypuppet.RoomQRCodeRequest{ Id: roomID, }) @@ -940,7 +939,7 @@ func (p *PuppetService) RoomQRCode(roomID string) (string, error) { // RoomMemberList ... func (p *PuppetService) RoomMemberList(roomID string) ([]string, error) { - log.Printf("PuppetService RoomMemberList(%s)\n", roomID) + log.Tracef("PuppetService RoomMemberList(%s)\n", roomID) response, err := p.grpcClient.RoomMemberList(context.Background(), &pbwechatypuppet.RoomMemberListRequest{ Id: roomID, }) @@ -952,7 +951,7 @@ func (p *PuppetService) RoomMemberList(roomID string) ([]string, error) { // RoomMemberRawPayload ... func (p *PuppetService) RoomMemberRawPayload(roomID string, contactID string) (*schemas.RoomMemberPayload, error) { - log.Printf("PuppetService RoomMemberRawPayload(%s, %s)\n", roomID, contactID) + log.Tracef("PuppetService RoomMemberRawPayload(%s, %s)\n", roomID, contactID) response, err := p.grpcClient.RoomMemberPayload(context.Background(), &pbwechatypuppet.RoomMemberPayloadRequest{ Id: roomID, MemberId: contactID, @@ -971,7 +970,7 @@ func (p *PuppetService) RoomMemberRawPayload(roomID string, contactID string) (* // SetRoomAnnounce ... func (p *PuppetService) SetRoomAnnounce(roomID, text string) error { - log.Printf("PuppetService SetRoomAnnounce(%s, %s)\n", roomID, text) + log.Tracef("PuppetService SetRoomAnnounce(%s, %s)\n", roomID, text) _, err := p.grpcClient.RoomAnnounce(context.Background(), &pbwechatypuppet.RoomAnnounceRequest{ Id: roomID, Text: &text, @@ -984,7 +983,7 @@ func (p *PuppetService) SetRoomAnnounce(roomID, text string) error { // RoomAnnounce ... func (p *PuppetService) RoomAnnounce(roomID string) (string, error) { - log.Printf("PuppetService RoomAnnounce(%s)\n", roomID) + log.Tracef("PuppetService RoomAnnounce(%s)\n", roomID) response, err := p.grpcClient.RoomAnnounce(context.Background(), &pbwechatypuppet.RoomAnnounceRequest{ Id: roomID, }) @@ -996,7 +995,7 @@ func (p *PuppetService) RoomAnnounce(roomID string) (string, error) { // RoomInvitationAccept ... func (p *PuppetService) RoomInvitationAccept(roomInvitationID string) error { - log.Printf("PuppetService RoomInvitationAccept(%s)\n", roomInvitationID) + log.Tracef("PuppetService RoomInvitationAccept(%s)\n", roomInvitationID) _, err := p.grpcClient.RoomInvitationAccept(context.Background(), &pbwechatypuppet.RoomInvitationAcceptRequest{ Id: roomInvitationID, }) @@ -1005,7 +1004,7 @@ func (p *PuppetService) RoomInvitationAccept(roomInvitationID string) error { // RoomInvitationRawPayload ... func (p *PuppetService) RoomInvitationRawPayload(id string) (*schemas.RoomInvitationPayload, error) { - log.Printf("PuppetService RoomInvitationRawPayload(%s)\n", id) + log.Tracef("PuppetService RoomInvitationRawPayload(%s)\n", id) response, err := p.grpcClient.RoomInvitationPayload(context.Background(), &pbwechatypuppet.RoomInvitationPayloadRequest{ Id: id, }) @@ -1027,7 +1026,7 @@ func (p *PuppetService) RoomInvitationRawPayload(id string) (*schemas.RoomInvita // FriendshipSearchPhone ... func (p *PuppetService) FriendshipSearchPhone(phone string) (string, error) { - log.Printf("PuppetService FriendshipSearchPhone(%s)\n", phone) + log.Tracef("PuppetService FriendshipSearchPhone(%s)\n", phone) response, err := p.grpcClient.FriendshipSearchPhone(context.Background(), &pbwechatypuppet.FriendshipSearchPhoneRequest{ Phone: phone, }) @@ -1039,7 +1038,7 @@ func (p *PuppetService) FriendshipSearchPhone(phone string) (string, error) { // FriendshipSearchWeixin ... func (p *PuppetService) FriendshipSearchWeixin(weixin string) (string, error) { - log.Printf("PuppetService FriendshipSearchWeixin(%s)\n", weixin) + log.Tracef("PuppetService FriendshipSearchWeixin(%s)\n", weixin) response, err := p.grpcClient.FriendshipSearchWeixin(context.Background(), &pbwechatypuppet.FriendshipSearchHandleRequest{ Weixin: weixin, }) @@ -1051,7 +1050,7 @@ func (p *PuppetService) FriendshipSearchWeixin(weixin string) (string, error) { // FriendshipRawPayload ... func (p *PuppetService) FriendshipRawPayload(id string) (*schemas.FriendshipPayload, error) { - log.Printf("PuppetService FriendshipRawPayload(%s)\n", id) + log.Tracef("PuppetService FriendshipRawPayload(%s)\n", id) response, err := p.grpcClient.FriendshipPayload(context.Background(), &pbwechatypuppet.FriendshipPayloadRequest{ Id: id, }) @@ -1075,7 +1074,7 @@ func (p *PuppetService) FriendshipRawPayload(id string) (*schemas.FriendshipPayl // FriendshipAdd ... func (p *PuppetService) FriendshipAdd(contactID, hello string) (err error) { - log.Printf("PuppetService FriendshipAdd(%s, %s)\n", contactID, hello) + log.Tracef("PuppetService FriendshipAdd(%s, %s)\n", contactID, hello) _, err = p.grpcClient.FriendshipAdd(context.Background(), &pbwechatypuppet.FriendshipAddRequest{ ContactId: contactID, Hello: hello, @@ -1085,7 +1084,7 @@ func (p *PuppetService) FriendshipAdd(contactID, hello string) (err error) { // FriendshipAccept ... func (p *PuppetService) FriendshipAccept(friendshipID string) (err error) { - log.Printf("PuppetService FriendshipAccept(%s)\n", friendshipID) + log.Tracef("PuppetService FriendshipAccept(%s)\n", friendshipID) _, err = p.grpcClient.FriendshipAccept(context.Background(), &pbwechatypuppet.FriendshipAcceptRequest{ Id: friendshipID, }) @@ -1094,7 +1093,7 @@ func (p *PuppetService) FriendshipAccept(friendshipID string) (err error) { // TagContactAdd ... func (p *PuppetService) TagContactAdd(id, contactID string) (err error) { - log.Printf("PuppetService TagContactAdd(%s, %s)\n", id, contactID) + log.Tracef("PuppetService TagContactAdd(%s, %s)\n", id, contactID) _, err = p.grpcClient.TagContactAdd(context.Background(), &pbwechatypuppet.TagContactAddRequest{ Id: id, ContactId: id, @@ -1104,7 +1103,7 @@ func (p *PuppetService) TagContactAdd(id, contactID string) (err error) { // TagContactRemove ... func (p *PuppetService) TagContactRemove(id, contactID string) (err error) { - log.Printf("PuppetService TagContactRemove(%s, %s)\n", id, contactID) + log.Tracef("PuppetService TagContactRemove(%s, %s)\n", id, contactID) _, err = p.grpcClient.TagContactRemove(context.Background(), &pbwechatypuppet.TagContactRemoveRequest{ Id: id, ContactId: contactID, @@ -1114,7 +1113,7 @@ func (p *PuppetService) TagContactRemove(id, contactID string) (err error) { // TagContactDelete ... func (p *PuppetService) TagContactDelete(id string) (err error) { - log.Printf("PuppetService TagContactDelete(%s)\n", id) + log.Tracef("PuppetService TagContactDelete(%s)\n", id) _, err = p.grpcClient.TagContactDelete(context.Background(), &pbwechatypuppet.TagContactDeleteRequest{ Id: id, }) @@ -1123,7 +1122,7 @@ func (p *PuppetService) TagContactDelete(id string) (err error) { // TagContactList ... func (p *PuppetService) TagContactList(contactID string) ([]string, error) { - log.Printf("PuppetService TagContactList(%s)\n", contactID) + log.Tracef("PuppetService TagContactList(%s)\n", contactID) request := &pbwechatypuppet.TagContactListRequest{} if contactID != "" { request.ContactId = contactID @@ -1137,7 +1136,7 @@ func (p *PuppetService) TagContactList(contactID string) ([]string, error) { // DirtyPayload ... func (p *PuppetService) DirtyPayload(payloadType schemas.PayloadType, id string) error { - log.Printf("PuppetService DirtyPayload(%v, %v)\n", payloadType, id) + log.Tracef("PuppetService DirtyPayload(%v, %v)\n", payloadType, id) err := p.Puppet.OnDirty(payloadType, id) if err != nil { return err @@ -1155,7 +1154,7 @@ func (p *PuppetService) DirtyPayload(payloadType schemas.PayloadType, id string) // MessageForward message forward func (p *PuppetService) MessageForward(conversationID string, messageID string) (string, error) { - log.Printf("PuppetService MessageForward(%v, %v)\n", conversationID, messageID) + log.Tracef("PuppetService MessageForward(%v, %v)\n", conversationID, messageID) request := &pbwechatypuppet.MessageForwardRequest{ MessageId: messageID, ConversationId: conversationID, diff --git a/wechaty-puppet-service/service_endpoint.go b/wechaty-puppet-service/service_endpoint.go index d7a2bd8..34edd2c 100644 --- a/wechaty-puppet-service/service_endpoint.go +++ b/wechaty-puppet-service/service_endpoint.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io/ioutil" - "log" "net/http" ) @@ -63,7 +62,7 @@ func (p *PuppetService) discoverServiceEndPoint() (endPoint ServiceEndPoint, err return endPoint, nil } if resp.StatusCode == http.StatusNotFound { - log.Printf("discoverServiceEndPoint() err: http.Status:%s\n", resp.Status) + log.Errorf("discoverServiceEndPoint() err: http.Status:%s\n", resp.Status) return endPoint, nil } return endPoint, fmt.Errorf("discoverServiceEndPoint() err: http.Status:%s", resp.Status) diff --git a/wechaty-puppet/events/events.go b/wechaty-puppet/events/events.go index 8650364..07bc40d 100644 --- a/wechaty-puppet/events/events.go +++ b/wechaty-puppet/events/events.go @@ -2,133 +2,133 @@ package events import ( - "log" - "reflect" - "sync" + logger "github.com/wechaty/go-wechaty/wechaty-puppet/log" + "reflect" + "sync" ) +var log = logger.L.WithField("module", "wechaty-puppet/events") + const ( - // DefaultMaxListeners is the number of max listeners per event - // default EventEmitters will print a warning if more than x listeners are - // added to it. This is a useful default which helps finding memory leaks. - // Defaults to 0, which means unlimited - DefaultMaxListeners = 0 - - // EnableWarning prints a warning when trying to add an event which it's len is equal to the maxListeners - // Defaults to false, which means it does not prints a warning - EnableWarning = false + // DefaultMaxListeners is the number of max listeners per event + // default EventEmitters will print a warning if more than x listeners are + // added to it. This is a useful default which helps finding memory leaks. + // Defaults to 0, which means unlimited + DefaultMaxListeners = 0 + + // EnableWarning prints a warning when trying to add an event which it's len is equal to the maxListeners + // Defaults to false, which means it does not prints a warning + EnableWarning = false ) type ( - // EventName is just a type of string, it's the event name - EventName interface{} - // Listener is the type of a Listener, it's a func which receives any,optional, arguments from the caller/emitter - Listener func(...interface{}) - // Events the type for registered listeners, it's just a map[string][]func(...interface{}) - Events map[EventName][]Listener - - // EventEmitter is the message/or/event manager - EventEmitter interface { - // AddListener is an alias for .On(eventName, listener). - AddListener(EventName, ...Listener) - // Emit fires a particular event, - // Synchronously calls each of the listeners registered for the event named - // eventName, in the order they were registered, - // passing the supplied arguments to each. - Emit(EventName, ...interface{}) - // EventNames returns an array listing the events for which the emitter has registered listeners. - // The values in the array will be strings. - EventNames() []EventName - // GetMaxListeners returns the max listeners for this emitter - // see SetMaxListeners - GetMaxListeners() int - // ListenerCount returns the length of all registered listeners to a particular event - ListenerCount(EventName) int - // Listeners returns a copy of the array of listeners for the event named eventName. - Listeners(EventName) []Listener - // On registers a particular listener for an event, func receiver parameter(s) is/are optional - On(EventName, ...Listener) - // Once adds a one time listener function for the event named eventName. - // The next time eventName is triggered, this listener is removed and then invoked. - Once(EventName, ...Listener) - // RemoveAllListeners removes all listeners, or those of the specified eventName. - // Note that it will remove the event itself. - // Returns an indicator if event and listeners were found before the remove. - RemoveAllListeners(EventName) bool - // RemoveListener removes given listener from the event named eventName. - // Returns an indicator whether listener was removed - RemoveListener(EventName, Listener) bool - // Clear removes all events and all listeners, restores Events to an empty value - Clear() - // SetMaxListeners obviously this function allows the MaxListeners - // to be decrease or increase. Set to zero for unlimited - SetMaxListeners(int) - // Len returns the length of all registered events - Len() int - } - - emitter struct { - maxListeners int - evtListeners Events - mu sync.Mutex - } + // EventName is just a type of string, it's the event name + EventName interface{} + // Listener is the type of a Listener, it's a func which receives any,optional, arguments from the caller/emitter + Listener func(...interface{}) + // Events the type for registered listeners, it's just a map[string][]func(...interface{}) + Events map[EventName][]Listener + + // EventEmitter is the message/or/event manager + EventEmitter interface { + // AddListener is an alias for .On(eventName, listener). + AddListener(EventName, ...Listener) + // Emit fires a particular event, + // Synchronously calls each of the listeners registered for the event named + // eventName, in the order they were registered, + // passing the supplied arguments to each. + Emit(EventName, ...interface{}) + // EventNames returns an array listing the events for which the emitter has registered listeners. + // The values in the array will be strings. + EventNames() []EventName + // GetMaxListeners returns the max listeners for this emitter + // see SetMaxListeners + GetMaxListeners() int + // ListenerCount returns the length of all registered listeners to a particular event + ListenerCount(EventName) int + // Listeners returns a copy of the array of listeners for the event named eventName. + Listeners(EventName) []Listener + // On registers a particular listener for an event, func receiver parameter(s) is/are optional + On(EventName, ...Listener) + // Once adds a one time listener function for the event named eventName. + // The next time eventName is triggered, this listener is removed and then invoked. + Once(EventName, ...Listener) + // RemoveAllListeners removes all listeners, or those of the specified eventName. + // Note that it will remove the event itself. + // Returns an indicator if event and listeners were found before the remove. + RemoveAllListeners(EventName) bool + // RemoveListener removes given listener from the event named eventName. + // Returns an indicator whether listener was removed + RemoveListener(EventName, Listener) bool + // Clear removes all events and all listeners, restores Events to an empty value + Clear() + // SetMaxListeners obviously this function allows the MaxListeners + // to be decrease or increase. Set to zero for unlimited + SetMaxListeners(int) + // Len returns the length of all registered events + Len() int + } + + emitter struct { + maxListeners int + evtListeners Events + mu sync.Mutex + } ) // CopyTo copies the event listeners to an EventEmitter func (e Events) CopyTo(emitter EventEmitter) { - if len(e) > 0 { - // register the events to/with their listeners - for evt, listeners := range e { - if len(listeners) > 0 { - emitter.AddListener(evt, listeners...) - } - } - } + if len(e) > 0 { + // register the events to/with their listeners + for evt, listeners := range e { + if len(listeners) > 0 { + emitter.AddListener(evt, listeners...) + } + } + } } // New returns a new, empty, EventEmitter func New() EventEmitter { - return &emitter{maxListeners: DefaultMaxListeners, evtListeners: Events{}} + return &emitter{maxListeners: DefaultMaxListeners, evtListeners: Events{}} } var ( - _ EventEmitter = &emitter{} - defaultEmitter = New() + _ EventEmitter = &emitter{} + defaultEmitter = New() ) // AddListener is an alias for .On(eventName, listener). func AddListener(evt EventName, listener ...Listener) { - defaultEmitter.AddListener(evt, listener...) + defaultEmitter.AddListener(evt, listener...) } func (e *emitter) AddListener(evt EventName, listener ...Listener) { - if len(listener) == 0 { - return - } + if len(listener) == 0 { + return + } - e.mu.Lock() - defer e.mu.Unlock() + e.mu.Lock() + defer e.mu.Unlock() - if e.evtListeners == nil { - e.evtListeners = Events{} - } + if e.evtListeners == nil { + e.evtListeners = Events{} + } - listeners := e.evtListeners[evt] + listeners := e.evtListeners[evt] - if e.maxListeners > 0 && len(listeners) == e.maxListeners { - if EnableWarning { - log.Printf(`(events) warning: possible EventEmitter memory ' + if e.maxListeners > 0 && len(listeners) == e.maxListeners { + log.Warnf(`(events) warning: possible EventEmitter memory ' leak detected. %d listeners added. ' Use emitter.SetMaxListeners(n int) to increase limit.`, len(listeners)) - } - return - } + return + } - if listeners == nil { - listeners = make([]Listener, e.maxListeners) - } + if listeners == nil { + listeners = make([]Listener, e.maxListeners) + } - e.evtListeners[evt] = append(listeners, listener...) + e.evtListeners[evt] = append(listeners, listener...) } // Emit fires a particular event, @@ -136,266 +136,264 @@ func (e *emitter) AddListener(evt EventName, listener ...Listener) { // eventName, in the order they were registered, // passing the supplied arguments to each. func Emit(evt EventName, data ...interface{}) { - defaultEmitter.Emit(evt, data...) + defaultEmitter.Emit(evt, data...) } func (e *emitter) Emit(evt EventName, data ...interface{}) { - if e.evtListeners == nil { - return // has no listeners to emit/speak yet - } - if listeners := e.evtListeners[evt]; len(listeners) > 0 { // len() should be just fine, but for any case on future... - for i := range listeners { - l := listeners[i] - if l != nil { - l(data...) - } - } - } + if e.evtListeners == nil { + return // has no listeners to emit/speak yet + } + if listeners := e.evtListeners[evt]; len(listeners) > 0 { // len() should be just fine, but for any case on future... + for i := range listeners { + l := listeners[i] + if l != nil { + l(data...) + } + } + } } // EventNames returns an array listing the events for which the emitter has registered listeners. // The values in the array will be strings. func EventNames() []EventName { - return defaultEmitter.EventNames() + return defaultEmitter.EventNames() } func (e *emitter) EventNames() []EventName { - if e.evtListeners == nil || e.Len() == 0 { - return nil - } - - names := make([]EventName, e.Len()) - i := 0 - for k := range e.evtListeners { - names[i] = k - i++ - } - return names + if e.evtListeners == nil || e.Len() == 0 { + return nil + } + + names := make([]EventName, e.Len()) + i := 0 + for k := range e.evtListeners { + names[i] = k + i++ + } + return names } // GetMaxListeners returns the max listeners for this emitter // see SetMaxListeners func GetMaxListeners() int { - return defaultEmitter.GetMaxListeners() + return defaultEmitter.GetMaxListeners() } func (e *emitter) GetMaxListeners() int { - return e.maxListeners + return e.maxListeners } // ListenerCount returns the length of all registered listeners to a particular event func ListenerCount(evt EventName) int { - return defaultEmitter.ListenerCount(evt) + return defaultEmitter.ListenerCount(evt) } func (e *emitter) ListenerCount(evt EventName) int { - if e.evtListeners == nil { - return 0 - } - length := 0 - - if evtListeners := e.evtListeners[evt]; evtListeners != nil { // length() should be just fine, but for any case on future... - for _, l := range evtListeners { - if l == nil { - continue - } - length++ - } - } - - return length + if e.evtListeners == nil { + return 0 + } + length := 0 + + if evtListeners := e.evtListeners[evt]; evtListeners != nil { // length() should be just fine, but for any case on future... + for _, l := range evtListeners { + if l == nil { + continue + } + length++ + } + } + + return length } // Listeners returns a copy of the array of listeners for the event named eventName. func Listeners(evt EventName) []Listener { - return defaultEmitter.Listeners(evt) + return defaultEmitter.Listeners(evt) } func (e *emitter) Listeners(evt EventName) []Listener { - if e.evtListeners == nil { - return nil - } - var listeners []Listener - if evtListeners := e.evtListeners[evt]; evtListeners != nil { - // do not pass any inactive/removed listeners(nil) - for _, l := range evtListeners { - if l == nil { - continue - } - - listeners = append(listeners, l) - } - - if len(listeners) > 0 { - return listeners - } - } - - return nil + if e.evtListeners == nil { + return nil + } + var listeners []Listener + if evtListeners := e.evtListeners[evt]; evtListeners != nil { + // do not pass any inactive/removed listeners(nil) + for _, l := range evtListeners { + if l == nil { + continue + } + + listeners = append(listeners, l) + } + + if len(listeners) > 0 { + return listeners + } + } + + return nil } // On registers a particular listener for an event, func receiver parameter(s) is/are optional func On(evt EventName, listener ...Listener) { - defaultEmitter.On(evt, listener...) + defaultEmitter.On(evt, listener...) } func (e *emitter) On(evt EventName, listener ...Listener) { - e.AddListener(evt, listener...) + e.AddListener(evt, listener...) } // Once adds a one time listener function for the event named eventName. // The next time eventName is triggered, this listener is removed and then invoked. func Once(evt EventName, listener ...Listener) { - defaultEmitter.Once(evt, listener...) + defaultEmitter.Once(evt, listener...) } func (e *emitter) Once(evt EventName, listener ...Listener) { - if len(listener) == 0 { - return - } - - var modifiedListeners []Listener - - if e.evtListeners == nil { - e.evtListeners = Events{} - } - - for i, l := range listener { - - idx := len(e.evtListeners) + i // get the next index (where this event should be added) and adds the i for the 'capacity' - - func(listener Listener, index int) { - fired := false - // remove the specific listener from the listeners before fire the real listener - modifiedListeners = append(modifiedListeners, func(data ...interface{}) { - if e.evtListeners == nil { - return - } - if !fired { - // make sure that we don't get a panic(index out of array or nil map here - if e.evtListeners[evt] != nil && (len(e.evtListeners[evt]) > index || index == 0) { - - e.mu.Lock() - //e.evtListeners[evt] = append(e.evtListeners[evt][:index], e.evtListeners[evt][index+1:]...) - // we do not must touch the order because of the pre-defined indexes, we need just to make this listener nil in order to be not executed, - // and make the len of listeners increase when listener is not nil, not just the len of listeners. - // so set this listener to nil - e.evtListeners[evt][index] = nil - e.mu.Unlock() - } - fired = true - listener(data...) - } - - }) - }(l, idx) - - } - e.AddListener(evt, modifiedListeners...) + if len(listener) == 0 { + return + } + + var modifiedListeners []Listener + + if e.evtListeners == nil { + e.evtListeners = Events{} + } + + for i, l := range listener { + + idx := len(e.evtListeners) + i // get the next index (where this event should be added) and adds the i for the 'capacity' + + func(listener Listener, index int) { + fired := false + // remove the specific listener from the listeners before fire the real listener + modifiedListeners = append(modifiedListeners, func(data ...interface{}) { + if e.evtListeners == nil { + return + } + if !fired { + // make sure that we don't get a panic(index out of array or nil map here + if e.evtListeners[evt] != nil && (len(e.evtListeners[evt]) > index || index == 0) { + + e.mu.Lock() + //e.evtListeners[evt] = append(e.evtListeners[evt][:index], e.evtListeners[evt][index+1:]...) + // we do not must touch the order because of the pre-defined indexes, we need just to make this listener nil in order to be not executed, + // and make the len of listeners increase when listener is not nil, not just the len of listeners. + // so set this listener to nil + e.evtListeners[evt][index] = nil + e.mu.Unlock() + } + fired = true + listener(data...) + } + + }) + }(l, idx) + + } + e.AddListener(evt, modifiedListeners...) } // RemoveAllListeners removes all listeners, or those of the specified eventName. // Note that it will remove the event itself. // Returns an indicator if event and listeners were found before the remove. func RemoveAllListeners(evt EventName) bool { - return defaultEmitter.RemoveAllListeners(evt) + return defaultEmitter.RemoveAllListeners(evt) } func (e *emitter) RemoveAllListeners(evt EventName) bool { - if e.evtListeners == nil { - return false // has nothing to remove - } - e.mu.Lock() - defer e.mu.Unlock() - if listeners := e.evtListeners[evt]; listeners != nil { - l := e.ListenerCount(evt) // in order to not get the len of any inactive/removed listeners - delete(e.evtListeners, evt) - if l > 0 { - return true - } - } - - return false + if e.evtListeners == nil { + return false // has nothing to remove + } + e.mu.Lock() + defer e.mu.Unlock() + if listeners := e.evtListeners[evt]; listeners != nil { + l := e.ListenerCount(evt) // in order to not get the len of any inactive/removed listeners + delete(e.evtListeners, evt) + if l > 0 { + return true + } + } + + return false } // RemoveListener removes the specified listener from the listener array for the event named eventName. func (e *emitter) RemoveListener(evt EventName, listener Listener) bool { - if e.evtListeners == nil { - return false - } + if e.evtListeners == nil { + return false + } - if listener == nil { - return false - } + if listener == nil { + return false + } - e.mu.Lock() - defer e.mu.Unlock() + e.mu.Lock() + defer e.mu.Unlock() - listeners := e.evtListeners[evt] + listeners := e.evtListeners[evt] - if listeners == nil { - return false - } + if listeners == nil { + return false + } - idx := -1 - listenerPointer := reflect.ValueOf(listener).Pointer() + idx := -1 + listenerPointer := reflect.ValueOf(listener).Pointer() - for index, item := range listeners { - itemPointer := reflect.ValueOf(item).Pointer() - if itemPointer == listenerPointer { - idx = index - break - } - } + for index, item := range listeners { + itemPointer := reflect.ValueOf(item).Pointer() + if itemPointer == listenerPointer { + idx = index + break + } + } - if idx < 0 { - return false - } + if idx < 0 { + return false + } - var modifiedListeners []Listener = nil + var modifiedListeners []Listener = nil - if len(listeners) > 1 { - modifiedListeners = append(listeners[:idx], listeners[idx+1:]...) - } + if len(listeners) > 1 { + modifiedListeners = append(listeners[:idx], listeners[idx+1:]...) + } - e.evtListeners[evt] = modifiedListeners + e.evtListeners[evt] = modifiedListeners - return true + return true } // Clear removes all events and all listeners, restores Events to an empty value func Clear() { - defaultEmitter.Clear() + defaultEmitter.Clear() } func (e *emitter) Clear() { - e.evtListeners = Events{} + e.evtListeners = Events{} } // SetMaxListeners obviously this function allows the MaxListeners // to be decrease or increase. Set to zero for unlimited func SetMaxListeners(n int) { - defaultEmitter.SetMaxListeners(n) + defaultEmitter.SetMaxListeners(n) } func (e *emitter) SetMaxListeners(n int) { - if n < 0 { - if EnableWarning { - log.Printf("(events) warning: MaxListeners must be positive number, tried to set: %d", n) - return - } - } - e.maxListeners = n + if n < 0 { + log.Warnf("(events) warning: MaxListeners must be positive number, tried to set: %d", n) + return + } + e.maxListeners = n } // Len returns the length of all registered events func Len() int { - return defaultEmitter.Len() + return defaultEmitter.Len() } func (e *emitter) Len() int { - if e.evtListeners == nil { - return 0 - } - return len(e.evtListeners) + if e.evtListeners == nil { + return 0 + } + return len(e.evtListeners) } diff --git a/wechaty-puppet/helper/fix_unknown_message.go b/wechaty-puppet/helper/fix_unknown_message.go index e2b89eb..17094e3 100644 --- a/wechaty-puppet/helper/fix_unknown_message.go +++ b/wechaty-puppet/helper/fix_unknown_message.go @@ -3,10 +3,12 @@ package helper import ( "encoding/xml" "fmt" + logger "github.com/wechaty/go-wechaty/wechaty-puppet/log" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" - "log" ) +var log = logger.L.WithField("module", "wechaty-puppet/helper") + // FixUnknownMessage 修复wechaty服务端不能解析的消息,尝试服务端去解析 func FixUnknownMessage(payload *schemas.MessagePayload) { if payload.Type != schemas.MessageTypeUnknown { @@ -15,7 +17,7 @@ func FixUnknownMessage(payload *schemas.MessagePayload) { msg := &Msg{} err := xml.Unmarshal([]byte(payload.Text), msg) if err != nil { - log.Printf("FixUnknownMessage raw:%s || err: %s", payload.Text, err) + log.Errorf("FixUnknownMessage raw:%s || err: %s", payload.Text, err) return } if msg.Appmsg.Type.Text == "36" { diff --git a/wechaty-puppet/log/log.go b/wechaty-puppet/log/log.go new file mode 100644 index 0000000..ecf073f --- /dev/null +++ b/wechaty-puppet/log/log.go @@ -0,0 +1,43 @@ +package log + +import ( + "github.com/sirupsen/logrus" + "os" +) + +// L logger +var L = logrus.New() + +// https://github.com/wechaty/wechaty/issues/2167 兼容 wecahty 社区的 log 等级 +var logLevels = map[string]string{ + "silent": "panic", + "silly": "trace", + "verbose": "trace", +} + +func init() { + level := os.Getenv("WECHATY_LOG") + if v, ok := logLevels[level]; ok { + level = v + } + logLevel, err := logrus.ParseLevel(level) + if err != nil { + logLevel = logrus.InfoLevel + } + L.SetLevel(logLevel) + L.SetFormatter(&logrus.TextFormatter{ + ForceColors: false, + DisableColors: false, + ForceQuote: false, + DisableQuote: false, + EnvironmentOverrideColors: false, + DisableTimestamp: false, + FullTimestamp: true, + TimestampFormat: "2006-01-02 15:04:05.000", + DisableSorting: false, + DisableLevelTruncation: false, + PadLevelText: false, + QuoteEmptyFields: false, + CallerPrettyfier: nil, + }) +} diff --git a/wechaty/config.go b/wechaty/config.go new file mode 100644 index 0000000..2d23e5a --- /dev/null +++ b/wechaty/config.go @@ -0,0 +1,5 @@ +package wechaty + +import logger "github.com/wechaty/go-wechaty/wechaty-puppet/log" + +var log = logger.L.WithField("module", "wechaty") diff --git a/wechaty/factory/config.go b/wechaty/factory/config.go new file mode 100644 index 0000000..8c3be8c --- /dev/null +++ b/wechaty/factory/config.go @@ -0,0 +1,5 @@ +package factory + +import logger "github.com/wechaty/go-wechaty/wechaty-puppet/log" + +var log = logger.L.WithField("module", "wechaty/factory") diff --git a/wechaty/factory/contact.go b/wechaty/factory/contact.go index b5a69ce..2e6bc57 100644 --- a/wechaty/factory/contact.go +++ b/wechaty/factory/contact.go @@ -2,7 +2,6 @@ package factory import ( "fmt" - "log" "sync" "github.com/wechaty/go-wechaty/wechaty-puppet/helper" @@ -66,7 +65,7 @@ func (c *ContactFactory) Find(query interface{}) _interface.IContact { return nil } if len(contacts) > 1 { - log.Printf("Contact Find() got more than one(%d) result\n", len(contacts)) + log.Warnf("Contact Find() got more than one(%d) result\n", len(contacts)) } for _, v := range contacts { if c.GetPuppet().ContactValidate(v.ID()) { @@ -80,7 +79,7 @@ func (c *ContactFactory) Find(query interface{}) _interface.IContact { func (c *ContactFactory) FindAll(query interface{}) []_interface.IContact { contactIds, err := c.GetPuppet().ContactSearch(query, nil) if err != nil { - log.Printf("Contact c.GetPuppet().ContactSearch() rejected: %s\n", err) + log.Errorf("Contact c.GetPuppet().ContactSearch() rejected: %s\n", err) return nil } @@ -111,7 +110,7 @@ func (c *ContactFactory) FindAll(query interface{}) []_interface.IContact { func (c *ContactFactory) Tags() []_interface.ITag { tagIDList, err := c.GetPuppet().TagContactList("") if err != nil { - log.Printf("ContactFactory Tags() exception: %s\n", err) + log.Errorf("ContactFactory Tags() exception: %s\n", err) return nil } tagList := make([]_interface.ITag, 0, len(tagIDList)) diff --git a/wechaty/factory/message.go b/wechaty/factory/message.go index ba8e6b3..fc83b0c 100644 --- a/wechaty/factory/message.go +++ b/wechaty/factory/message.go @@ -5,7 +5,6 @@ import ( "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" _interface "github.com/wechaty/go-wechaty/wechaty/interface" "github.com/wechaty/go-wechaty/wechaty/user" - "log" ) type MessageFactory struct { @@ -25,15 +24,17 @@ func (m *MessageFactory) Find(query interface{}) _interface.IMessage { case *schemas.MessageQueryFilter: q = v default: - log.Println("not support query type") + log.Error("not support query type") + // TODO 返回 err 更好 return nil } messages := m.FindAll(q) if len(messages) < 1 { + // TODO 返回 err 更好 return nil } if len(messages) > 1 { - log.Printf("Message FindAll() got more than one(%d) result\n", len(messages)) + log.Errorf("Message FindAll() got more than one(%d) result\n", len(messages)) } return messages[0] } @@ -43,7 +44,7 @@ func (m *MessageFactory) FindAll(query *schemas.MessageQueryFilter) []_interface var err error defer func() { if err != nil { - log.Printf("MessageFactory FindAll rejected: %s\n", err) + log.Errorf("MessageFactory FindAll rejected: %s\n", err) } }() messageIDs, err := m.GetPuppet().MessageSearch(query) diff --git a/wechaty/factory/room.go b/wechaty/factory/room.go index 6a9a0d3..b347c98 100644 --- a/wechaty/factory/room.go +++ b/wechaty/factory/room.go @@ -2,7 +2,6 @@ package factory import ( "errors" - "log" "sync" "github.com/wechaty/go-wechaty/wechaty-puppet/helper" @@ -44,7 +43,7 @@ func (r *RoomFactory) Create(contactList []_interface.IContact, topic string) (_ func (r *RoomFactory) FindAll(query *schemas.RoomQueryFilter) []_interface.IRoom { roomIDList, err := r.GetPuppet().RoomSearch(query) if err != nil { - log.Println("RoomFactory err: ", err) + log.Error("RoomFactory err: ", err) return nil } if len(roomIDList) == 0 { @@ -77,7 +76,8 @@ func (r *RoomFactory) Find(query interface{}) _interface.IRoom { case *schemas.RoomQueryFilter: q = v default: - log.Printf("not support query type %T\n", query) + log.Errorf("not support query type %T\n", query) + // TODO 应该返回 err return nil } roomList := r.FindAll(q) @@ -89,6 +89,7 @@ func (r *RoomFactory) Find(query interface{}) _interface.IRoom { return room } } + // TODO 应该返回 err return nil } diff --git a/wechaty/plugin.go b/wechaty/plugin.go index 9ae3294..0085383 100644 --- a/wechaty/plugin.go +++ b/wechaty/plugin.go @@ -3,7 +3,6 @@ package wechaty import ( "fmt" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" - "log" "reflect" "runtime/debug" "sync" @@ -51,8 +50,8 @@ func (p *Plugin) registerPluginEvent(wechaty *Wechaty) { f := func(data ...interface{}) { defer func() { if err := recover(); err != nil { - log.Println("panic: ", err) - log.Println(string(debug.Stack())) + log.Error("panic: ", err) + log.Error(string(debug.Stack())) wechaty.events.Emit(schemas.PuppetEventNameError, NewContext(), fmt.Errorf("panic: event %s %v", pluginEvent.name, err)) } }() diff --git a/wechaty/user/config.go b/wechaty/user/config.go new file mode 100644 index 0000000..a1ff46d --- /dev/null +++ b/wechaty/user/config.go @@ -0,0 +1,5 @@ +package user + +import logger "github.com/wechaty/go-wechaty/wechaty-puppet/log" + +var log = logger.L.WithField("module", "wechaty/user") diff --git a/wechaty/user/contact.go b/wechaty/user/contact.go index 977206c..78a13c3 100644 --- a/wechaty/user/contact.go +++ b/wechaty/user/contact.go @@ -23,8 +23,6 @@ package user import ( "fmt" - "log" - "github.com/wechaty/go-wechaty/wechaty-puppet/filebox" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/config" @@ -160,7 +158,7 @@ func (c *Contact) City() string { func (c *Contact) Avatar() *filebox.FileBox { avatar, err := c.GetPuppet().ContactAvatar(c.Id) if err != nil { - log.Printf("Contact Avatar() exception: %s\n", err) + log.Errorf("Contact Avatar() exception: %s\n", err) return config.QRCodeForChatie() } return avatar @@ -187,7 +185,7 @@ func (c *Contact) SetAlias(newAlias string) { var err error defer func() { if err != nil { - log.Printf("Contact SetAlias(%s) rejected: %s\n", newAlias, err) + log.Errorf("Contact SetAlias(%s) rejected: %s\n", newAlias, err) } }() err = c.GetPuppet().SetContactAlias(c.Id, newAlias) @@ -196,14 +194,14 @@ func (c *Contact) SetAlias(newAlias string) { } err = c.GetPuppet().DirtyPayload(schemas.PayloadTypeContact, c.Id) if err != nil { - log.Println("SetAlias DirtyPayload err:", err) + log.Error("SetAlias DirtyPayload err:", err) } c.payload, err = c.GetPuppet().ContactPayload(c.Id) if err != nil { - log.Println("SetAlias ContactPayload err:", err) + log.Error("SetAlias ContactPayload err:", err) return } if c.payload.Alias != newAlias { - log.Printf("Contact SetAlias(%s) sync with server fail: set(%s) is not equal to get(%s)\n", newAlias, newAlias, c.payload.Alias) + log.Errorf("Contact SetAlias(%s) sync with server fail: set(%s) is not equal to get(%s)\n", newAlias, newAlias, c.payload.Alias) } } diff --git a/wechaty/user/room.go b/wechaty/user/room.go index 2a0548a..fd309e1 100644 --- a/wechaty/user/room.go +++ b/wechaty/user/room.go @@ -2,7 +2,6 @@ package user import ( "fmt" - "log" "strings" "github.com/wechaty/go-wechaty/wechaty-puppet/filebox" @@ -210,7 +209,7 @@ func (r *Room) Topic() string { } memberList, err := r.memberList() if err != nil { - log.Println("Room Topic err: ", err) + log.Error("Room Topic err: ", err) return "" } i := 1 diff --git a/wechaty/user/room_invitation.go b/wechaty/user/room_invitation.go index 2307652..4f7623c 100644 --- a/wechaty/user/room_invitation.go +++ b/wechaty/user/room_invitation.go @@ -3,7 +3,6 @@ package user import ( "encoding/json" "fmt" - "log" "time" _interface "github.com/wechaty/go-wechaty/wechaty/interface" @@ -52,7 +51,7 @@ func (ri *RoomInvitation) Accept() error { if err != nil { return err } - log.Printf("RoomInvitation accept() with room(%s) & inviter(%s) ready()", topic, inviter) + log.Tracef("RoomInvitation accept() with room(%s) & inviter(%s) ready()", topic, inviter) return inviter.Ready(false) } diff --git a/wechaty/wechaty.go b/wechaty/wechaty.go index 081dd49..84db6e4 100644 --- a/wechaty/wechaty.go +++ b/wechaty/wechaty.go @@ -34,7 +34,6 @@ import ( "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/factory" "github.com/wechaty/go-wechaty/wechaty/interface" - "log" "os" "os/signal" "reflect" @@ -93,8 +92,8 @@ func (w *Wechaty) registerEvent(name schemas.PuppetEventName, f interface{}) { w.events.On(name, func(data ...interface{}) { defer func() { if err := recover(); err != nil { - log.Println("panic: ", err) - log.Println(string(debug.Stack())) + log.Error("panic: ", err) + log.Error(string(debug.Stack())) w.emit(schemas.PuppetEventNameError, NewContext(), fmt.Errorf("panic: event %s %v", name, err)) } }() @@ -209,7 +208,7 @@ func (w *Wechaty) emit(name schemas.PuppetEventName, data ...interface{}) { // init puppet func (w *Wechaty) initPuppet() error { if w.puppet != nil { - log.Fatalln("Puppet already inited.") + log.Warn("Puppet already inited.") return nil } if w.memoryCard == nil { @@ -259,26 +258,26 @@ func (w *Wechaty) Start() error { if w.memoryCard == nil { w.memoryCard, err = mc.NewMemoryCard(w.name) if err != nil { - log.Println("memory card new err: ", err) + log.Error("memory card new err: ", err) return err } } err = w.memoryCard.Load() if err != nil { - log.Println("memory card load err: ", err) + log.Error("memory card load err: ", err) return err } err = w.initPuppet() if err != nil { - log.Println("memory card load err: ", err) + log.Error("memory card load err: ", err) return err } err = w.puppet.Start() if err != nil { - log.Println("puppet start err: ", err) + log.Error("puppet start err: ", err) return err } @@ -322,7 +321,7 @@ func (w *Wechaty) initPuppetEventBridge() { w.puppet.On(name, func(i ...interface{}) { contact := w.contact.LoadSelf(i[0].(*schemas.EventLoginPayload).ContactId) if err := contact.Ready(false); err != nil { - log.Printf("emit login contact.Ready err: %s\n", err.Error()) + log.Errorf("emit login contact.Ready err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -333,7 +332,7 @@ func (w *Wechaty) initPuppetEventBridge() { payload := i[0].(*schemas.EventLogoutPayload) contact := w.contact.LoadSelf(payload.ContactId) if err := contact.Ready(false); err != nil { - log.Printf("emit logout contact.Ready err: %s\n", err.Error()) + log.Errorf("emit logout contact.Ready err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -349,7 +348,7 @@ func (w *Wechaty) initPuppetEventBridge() { messageID := i[0].(*schemas.EventMessagePayload).MessageId message := w.message.Load(messageID) if err := message.Ready(); err != nil { - log.Printf("emit message message.Ready() err: %s\n", err.Error()) + log.Errorf("emit message message.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -359,7 +358,7 @@ func (w *Wechaty) initPuppetEventBridge() { w.puppet.On(name, func(i ...interface{}) { friendship := w.friendship.Load(i[0].(*schemas.EventFriendshipPayload).FriendshipID) if err := friendship.Ready(); err != nil { - log.Printf("emit friendship friendship.Ready() err: %s\n", err.Error()) + log.Errorf("emit friendship friendship.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -379,7 +378,7 @@ func (w *Wechaty) initPuppetEventBridge() { payload := i[0].(*schemas.EventRoomJoinPayload) room := w.room.Load(payload.RoomId) if err := room.Sync(); err != nil { - log.Printf("emit roomjoin room.Sync() err: %s\n", err.Error()) + log.Errorf("emit roomjoin room.Sync() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -387,7 +386,7 @@ func (w *Wechaty) initPuppetEventBridge() { for _, id := range payload.InviteeIdList { c := w.contact.Load(id) if err := c.Ready(false); err != nil { - log.Printf("emit roomjoin contact.Ready() err: %s\n", err.Error()) + log.Errorf("emit roomjoin contact.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -395,7 +394,7 @@ func (w *Wechaty) initPuppetEventBridge() { } inviter := w.contact.Load(payload.InviterId) if err := inviter.Ready(false); err != nil { - log.Printf("emit roomjoin inviter.Ready() err: %s\n", err.Error()) + log.Errorf("emit roomjoin inviter.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -406,7 +405,7 @@ func (w *Wechaty) initPuppetEventBridge() { payload := i[0].(*schemas.EventRoomLeavePayload) room := w.room.Load(payload.RoomId) if err := room.Sync(); err != nil { - log.Printf("emit roomleave room.Sync() err: %s\n", err.Error()) + log.Errorf("emit roomleave room.Sync() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -414,7 +413,7 @@ func (w *Wechaty) initPuppetEventBridge() { for _, id := range payload.RemoveeIdList { c := w.contact.Load(id) if err := c.Ready(false); err != nil { - log.Printf("emit roomleave contact.Ready() err: %s\n", err.Error()) + log.Errorf("emit roomleave contact.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -422,7 +421,7 @@ func (w *Wechaty) initPuppetEventBridge() { } remover := w.contact.Load(payload.RemoverId) if err := remover.Ready(false); err != nil { - log.Printf("emit roomleave inviter.Ready() err: %s\n", err.Error()) + log.Errorf("emit roomleave inviter.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -441,13 +440,13 @@ func (w *Wechaty) initPuppetEventBridge() { payload := i[0].(*schemas.EventRoomTopicPayload) room := w.room.Load(payload.RoomId) if err := room.Sync(); err != nil { - log.Printf("emit roomtopic room.Sync() err: %s\n", err.Error()) + log.Errorf("emit roomtopic room.Sync() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } changer := w.contact.Load(payload.ChangerId) if err := changer.Ready(false); err != nil { - log.Printf("emit roomtopic changer.Ready() err: %s\n", err.Error()) + log.Errorf("emit roomtopic changer.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -463,13 +462,13 @@ func (w *Wechaty) initPuppetEventBridge() { case schemas.PayloadTypeRoomMember, schemas.PayloadTypeContact: if err := w.contact.Load(payload.PayloadId).Ready(true); err != nil { - log.Printf("emit dirty contact.Ready() err: %s\n", err.Error()) + log.Errorf("emit dirty contact.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } case schemas.PayloadTypeRoom: if err := w.room.Load(payload.PayloadId).Ready(true); err != nil { - log.Printf("emit dirty room.Ready() err: %s\n", err.Error()) + log.Errorf("emit dirty room.Ready() err: %s\n", err.Error()) w.emit(schemas.PuppetEventNameError, NewContext(), err) return } @@ -483,7 +482,7 @@ func (w *Wechaty) initPuppetEventBridge() { case schemas.PayloadTypeUnknown: fallthrough default: - log.Printf("unknown payload type: %s\n", payload.PayloadType) + log.Errorf("unknown payload type: %s\n", payload.PayloadType) } }) default: diff --git a/wechaty/wechaty_test.go b/wechaty/wechaty_test.go index a261d83..bb086a3 100644 --- a/wechaty/wechaty_test.go +++ b/wechaty/wechaty_test.go @@ -2,7 +2,6 @@ package wechaty import ( "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" - "log" "testing" )