调试

调试 Redis 堆栈函数的方法

Redis 堆栈 Redis 社区版 Redis 企业软件 Redis 云 Redis 社区版 适用于 Kubernetes 的 Redis Enterprise 客户

概述

您可以使用两种方法来调试 Redis Stack 函数:

  1. 明智地使用redis.log函数,该函数写入 Redis 日志文件。
  2. 使用 Redis pub/sub

redis.log

如果您有权访问 Redis 日志文件,redis.log是调试时使用的好方法。但是,有一个缺点。Redis Cloud 用户无权访问 Redis 日志文件,在自托管安装中,只有系统管理员才能访问这些文件,这很常见。幸运的是,您还可以使用 Redis pub/sub,这将在下一节中讨论。

您无需执行任何特殊作即可使用redis.log,因为它始终可用。下面是一个示例:

#!js api_version=1.0 name=lib

redis.registerFunction('hello', ()=> {
  redis.log('Hello log')
  return 'Hello from an external file'
})

After loading the library and executing the function with TFCALL, you'll see something like the following in your Redis log file:

45718:M 01 Nov 2023 07:02:40.593 * <redisgears_2> Hello log

Use Redis pub/sub

If you don't have access to your Redis database log files, you can use pub/sub. The following example demonstrates how to use the client.call API to publish to a pub/sub channel.

#!js api_version=1.0 name=lib

const logChannel = 'tfLogChannel'

function publog(client, message) {
  client.call('publish', logChannel, message)
}

redis.registerFunction('tflog', (client) => {
  publog(client, 'sample pub/sub log message')
  return 'sample'
})

In a CLI session, subscribe to the tfLogChannel channel and watch for messages.

$ redis-cli
127.0.0.1:6379> subscribe tfLogChannel
1) "subscribe"
2) "tfLogChannel"
3) (integer) 1
Reading messages... (press Ctrl-C to quit or any key to type command)

In another CLI session, load the library, replacing what was already there, and then call the new function:

127.0.0.1:6379> TFCALL lib.tflog 0
"sample"

You'll see the following in the previous CLI session:

1) "message"
2) "tfLogChannel"
3) "sample pub/sub log message"

There is a downside to using pub/sub. Redis pub/sub provides at-most-once message delivery semantics, which means that once a message is sent, it won't be sent again. So, if a message isn't consumed, it's gone forever. This is likely okay for debugging, but for the longer term, redis.log is the better solution for log persistence.