Skip to content

Commit

Permalink
add redis logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Dirk Moermans committed Oct 11, 2021
1 parent d1f7bce commit 10877e9
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
5 changes: 4 additions & 1 deletion cmd_scripting.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,13 @@ func (m *Miniredis) runLuaScript(c *server.Peer, script string, args []string) b
}
l.SetGlobal("ARGV", argvTable)

redisFuncs := mkLuaFuncs(m.srv, c)
redisFuncs, redisConstants := mkLua(m.srv, c)
// Register command handlers
l.Push(l.NewFunction(func(l *lua.LState) int {
mod := l.RegisterModule("redis", redisFuncs).(*lua.LTable)
for k, v := range redisConstants {
mod.RawSetString(k, v)
}
l.Push(mod)
return 1
}))
Expand Down
11 changes: 11 additions & 0 deletions cmd_scripting_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,17 @@ func TestCJSON(t *testing.T) {
)
}

func TestLog(t *testing.T) {
s, err := Run()
ok(t, err)
defer s.Close()
c, err := proto.Dial(s.Addr())
ok(t, err)
defer c.Close()
mustNil(t, c,
"EVAL", "redis.log(redis.LOG_NOTICE, 'hello')", "0")
}

func TestSha1Hex(t *testing.T) {
s, err := Run()
ok(t, err)
Expand Down
27 changes: 25 additions & 2 deletions lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@ import (
"github.com/alicebob/miniredis/v2/server"
)

func mkLuaFuncs(srv *server.Server, c *server.Peer) map[string]lua.LGFunction {
var luaRedisConstants = map[string]lua.LValue{
"LOG_DEBUG": lua.LNumber(0),
"LOG_VERBOSE": lua.LNumber(1),
"LOG_NOTICE": lua.LNumber(2),
"LOG_WARNING": lua.LNumber(3),
}

func mkLua(srv *server.Server, c *server.Peer) (map[string]lua.LGFunction, map[string]lua.LValue) {
mkCall := func(failFast bool) func(l *lua.LState) int {
// one server.Ctx for a single Lua run
pCtx := &connCtx{}
Expand Down Expand Up @@ -107,6 +114,22 @@ func mkLuaFuncs(srv *server.Server, c *server.Peer) map[string]lua.LGFunction {
l.Push(res)
return 1
},
"log": func(l *lua.LState) int {
v := l.Get(1)
level, ok := v.(lua.LNumber)
if !ok {
l.Error(lua.LString("wrong type for the level"), 1)
return 0
}
v = l.Get(2)
msg, ok := v.(lua.LString)
if !ok {
l.Error(lua.LString("wrong number or type of arguments"), 1)
return 0
}
fmt.Printf("%v: %v", level, msg)
return 0
},
"status_reply": func(l *lua.LState) int {
v := l.Get(1)
msg, ok := v.(lua.LString)
Expand All @@ -133,7 +156,7 @@ func mkLuaFuncs(srv *server.Server, c *server.Peer) map[string]lua.LGFunction {
// ignored
return 1
},
}
}, luaRedisConstants
}

func luaToRedis(l *lua.LState, c *server.Peer, value lua.LValue) {
Expand Down

0 comments on commit 10877e9

Please sign in to comment.