Skip to content

Commit

Permalink
feat : Optimize log printing interface #26
Browse files Browse the repository at this point in the history
  • Loading branch information
taotao committed May 21, 2024
1 parent ccfc876 commit 076ed2f
Show file tree
Hide file tree
Showing 10 changed files with 229 additions and 156 deletions.
5 changes: 3 additions & 2 deletions driver/bot/behavior/behavior.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ type Tree struct {

Wait int32 `xml:"wait"`

Loop int32 `xml:"loop"` // 用于记录循环节点的循环x次数
Code string `xml:"code"`
Loop int32 `xml:"loop"` // 用于记录循环节点的循环x次数
Code string `xml:"code"`
Alias string `xml:"alias"` // 用于记录别名

root INod

Expand Down
12 changes: 9 additions & 3 deletions driver/bot/behavior/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ type INod interface {
}

type Node struct {
id string
ty string
id string
name string
ty string

child []INod
parent INod
Expand All @@ -53,6 +54,7 @@ type Node struct {
func (n *Node) Init(t *Tree, parent INod) {
n.id = t.ID
n.ty = t.Ty
n.name = t.Alias

n.parent = parent
}
Expand All @@ -61,9 +63,13 @@ func (a *Node) ID() string {
return a.id
}

func (a *Node) GetShortID() string {
return a.id[len(a.id)-12:]
}

// Name 返回节点的名称
func (a *Node) Name() string {
return ""
return a.name
}

func (a *Node) Type() string {
Expand Down
20 changes: 15 additions & 5 deletions driver/bot/behavior/tick.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"time"

"github.com/pojol/gobot/driver/bot/pool"
"github.com/pojol/gobot/driver/utils"
Expand Down Expand Up @@ -82,7 +83,7 @@ ext:
return state, changestr, err
}

func (t *Tick) Do(mod Mode) (state string, end bool, logs []string) {
func (t *Tick) Do(mod Mode) (state string, end bool) {

nods := t.blackboard.GetOpenNods()
t.blackboard.ThreadInfoReset()
Expand All @@ -91,6 +92,13 @@ func (t *Tick) Do(mod Mode) (state string, end bool, logs []string) {
var msg string

for _, n := range nods {
// 要将一个节点的日志收集到一起,将alias写入到meta中
if n.getType() == SCRIPT && mod == Step {
log := time.Now().Format("2006-01-02 15:04:05") + " tick " + n.getBase().Name() + " " + n.getBase().GetShortID() + " =>"
t.bs.L.DoString(`
log.info("` + log + `")
`)
}
err = n.onTick(t)

state, msg, parseerr = t.stateCheck(mod, n.getType())
Expand All @@ -102,12 +110,14 @@ func (t *Tick) Do(mod Mode) (state string, end bool, logs []string) {
}

if err != nil {
logs = append(logs, fmt.Sprintf("<b><u>check err</u></b> thread:%v name:%v id:%v\n%v",
log := fmt.Sprintf("<b><u>check err</u></b> thread:%v name:%v id:%v\n%v",
n.getBase().getThread(),
n.getBase().ID(),
n.getBase().Name(),
err.Error()),
)
err.Error())
t.bs.L.DoString(`
log.info("` + log + `")
`)
}
if parseerr != nil {
//threadInfo.ErrMsg = fmt.Sprintf("%v parse err %v", threadInfo.ErrMsg, parseerr.Error())
Expand Down Expand Up @@ -143,5 +153,5 @@ func (t *Tick) Do(mod Mode) (state string, end bool, logs []string) {
}

ext:
return state, end, logs
return state, end
}
38 changes: 3 additions & 35 deletions driver/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,21 +166,13 @@ func NewWithBehaviorTree(path string, bt *behavior.Tree, mode behavior.Mode, nam
fmt.Println("set bot name", err.Error())
}

bot.addLog(fmt.Sprintf("create bot id %v name %v success", bot.id, bot.name))

return bot
}

func (b *Bot) loopThread(doneCh chan<- string, errch chan<- ErrInfo) {

for {
state, end, logs := b.tick.Do(b.mod)
if len(logs) != 0 {
for _, log := range logs {
b.addLog(log)
}
}

state, end := b.tick.Do(b.mod)
if end {
doneCh <- b.id
goto ext
Expand Down Expand Up @@ -216,13 +208,7 @@ func (b *Bot) RunByBlock() error {
}()

for {
state, end, logs := b.tick.Do(b.mod)
if len(logs) != 0 {
for _, log := range logs {
b.addLog(log)
}
}

state, end := b.tick.Do(b.mod)
if end {
return nil
}
Expand Down Expand Up @@ -275,8 +261,6 @@ func (b *Bot) close() {
} else {
pool.FreeState(b.bs)
}

b.addLog(fmt.Sprintf("close bot id %v name %v success", b.id, b.name))
}

// PopLog - 弹出一条日志
Expand All @@ -286,16 +270,6 @@ func (b *Bot) PopLog() string {
return line
}

func (b *Bot) addLog(log string) {
fmt.Println("=>", log)

log = time.Now().Format("2006-01-02 15:04:05") + " =================>\n" + log

if b.mod != behavior.Thread {
b.bs.LogMod.Push(log)
}
}

type State int32

// 系统内部错误
Expand All @@ -312,13 +286,7 @@ func (b *Bot) RunByStep() State {
defer stepmu.Unlock()

// 这边的错误日志需要记录下
state, end, logs := b.tick.Do(b.mod)
if len(logs) != 0 {
for _, log := range logs {
b.addLog(log)
}
}

state, end := b.tick.Do(b.mod)
if end {
return SEnd
}
Expand Down
4 changes: 3 additions & 1 deletion driver/bot/pool/lua_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ func _new_state() *BotState {
b.L.PreloadModule("base64", b.base64Mod.Loader)
b.L.PreloadModule("mgo", b.mgoMod.Loader)
b.L.PreloadModule("md5", b.md5Mod.Loader)
b.L.PreloadModule("log", b.LogMod.Loader)

// 全局 log
b.LogMod.Loader(b.L)

return b
}
Expand Down
102 changes: 102 additions & 0 deletions driver/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package driver

import (
"context"
"flag"
"fmt"
"net/http"
"runtime"
"strconv"

"github.com/pojol/gobot/driver/factory"
"github.com/pojol/gobot/driver/mock"
"github.com/pojol/gobot/driver/openapi"
"github.com/pojol/gobot/driver/utils"
lua "github.com/yuin/gopher-lua"
)

const (
// Version of gobot driver
Version = "v0.4.4"

banner = `
__ __
/\ \ /\ \__
__ ___\ \ \____ ___\ \ ,_\
/'_ '\ / __'\ \ '__'\ / __'\ \ \
/\ \L\ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_
\ \____ \ \____/\ \_,__/\ \____/\ \__\
\/___L\ \/___/ \/___/ \/___/ \/__/
/\____/
\_/__/ %s
`
)

func Run() {
defer func() {
if err := recover(); err != nil {
var buf [4096]byte
n := runtime.Stack(buf[:], false)
fmt.Println("panic:", string(buf[:n]))
}
}()

f := utils.InitFlag()
flag.Parse()
if utils.ShowUseage() {
return
}

fmt.Printf(banner, Version)

botFactory, err := factory.Create(
factory.WithDatabase(f.DBType),
factory.WithClusterMode(f.Cluster),
)
if err != nil {
panic(err)
}
defer botFactory.Close()

L := lua.NewState()
defer L.Close()
L.DoFile(f.ScriptPath + "/" + "message.lua")
byteOrder := L.GetGlobal("ByteOrder").String()

if f.OpenHttpMock != 0 {
ms := mock.NewHttpServer()
go ms.Start(":" + strconv.Itoa(f.OpenHttpMock))
defer ms.Close()
}

if f.OpenTcpMock != 0 {
tcpls := mock.StarTCPServer(byteOrder, ":"+strconv.Itoa(f.OpenTcpMock))
defer tcpls.Close()
}

if f.OpenWSMock != 0 {
ws := mock.StartWebsocketServe(byteOrder, ":"+strconv.Itoa(f.OpenWSMock))
defer ws.Close()
}

go func() {
http.ListenAndServe(":6060", nil)
}()

// 查看有没有未完成的队列
factory.Global.CheckTaskHistory()

openApiPort := 8888
if f.OpenAPIPort != 0 {
openApiPort = f.OpenAPIPort
}

e := openapi.Start(openApiPort)
defer e.Close()

// Stop the service gracefully.
if err := e.Shutdown(context.TODO()); err != nil {
panic(err)
}
}
65 changes: 53 additions & 12 deletions driver/script/module/log.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package script

import (
"encoding/json"
"fmt"
"sync"

"github.com/pojol/gobot/driver/utils"
lua "github.com/yuin/gopher-lua"
)

Expand All @@ -12,10 +15,15 @@ type LogModule struct {
}

func (lm *LogModule) Loader(L *lua.LState) int {
mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
log := L.NewTable()

// 设置 log 的方法
L.SetFuncs(log, map[string]lua.LGFunction{
"info": lm.info,
})
L.Push(mod)

L.SetGlobal("log", log)

return 1
}

Expand All @@ -24,19 +32,50 @@ func (lm *LogModule) info(L *lua.LState) int {
lm.Lock()
defer lm.Unlock()

info := L.ToString(1)
var info string

// 获取参数数量
n := L.GetTop()
if n == 0 {
return 0
}

for i := 1; i <= n; i++ {
arg := L.Get(i)
switch arg.Type() {
case lua.LTNumber:
info += fmt.Sprintf("%v\t", arg.(lua.LNumber))
case lua.LTString:
info += fmt.Sprintf("%v\t", string(arg.(lua.LString)))
case lua.LTBool:
b := bool(arg.(lua.LBool))
if b {
info += "true\t"
} else {
info += "false\t"
}
case lua.LTNil:
info += "nil\t"
case lua.LTTable:
m := make(map[string]interface{})
var err error
m, err = utils.Table2Map(arg.(*lua.LTable))
if err != nil {
fmt.Println("Table2Map error", err)
}
tablestr, _ := json.MarshalIndent(&m, "", " ")
info += string(tablestr) + "\n"
// 根据需要处理其他类型
default:
info += fmt.Sprintf("arg%d is of type %s\n", i, arg.Type().String())
}
}

lm.logs = append(lm.logs, info)

return 0
}

// Push - golang端添加一行日志
func (lm *LogModule) Push(log string) {
lm.Lock()
lm.logs = append(lm.logs, log)
lm.Unlock()
}

func (lm *LogModule) Pop() string {
lm.Lock()
defer lm.Unlock()
Expand All @@ -45,8 +84,10 @@ func (lm *LogModule) Pop() string {
if n == 0 {
return ""
}
x := lm.logs[n-1]
lm.logs = lm.logs[0 : n-1]

// 从头部取出元素
x := lm.logs[0]
lm.logs = lm.logs[1:n]

return x
}
Expand Down
Loading

0 comments on commit 076ed2f

Please sign in to comment.