MONITOR Command
The MONITOR command streams every command processed by the Valkey server back to the client in real time. It is intended for debugging and development only.
How It Works
Section titled “How It Works”When you create a MonitorClient, GLIDE opens a dedicated connection and sends the MONITOR command. The server begins streaming command records back over that connection. Each record contains the timestamp, database index, client address, command name, and arguments.
MONITOR is only supported for standalone (non-cluster) connections. Attempting to use it with a cluster configuration will result in an error.
GLIDE clients generally provide two modes for consuming monitor messages:
- Callback mode: Provide a callback function at creation time that is invoked for every incoming message.
- Queue mode — Messages are queued internally and retrieved by polling.
Examples
Section titled “Examples”import glide.api.MonitorClient;import glide.api.models.commands.MonitorMsg;import glide.api.models.configuration.GlideClientConfiguration;import glide.api.models.configuration.NodeAddress;
GlideClientConfiguration config = GlideClientConfiguration.builder() .address(NodeAddress.builder().host("localhost").port(6379).build()) .build();
// Callback modetry (MonitorClient monitor = MonitorClient.create(config, (MonitorMsg msg) -> System.out.printf("%.6f [%d] %s %s %s%n", msg.timestamp(), msg.db(), msg.clientAddr(), msg.command(), msg.args()))) { // Run commands on a separate client — the callback will print each one. Thread.sleep(5000);}
// Queue modetry (MonitorClient monitor = MonitorClient.create(config)) { MonitorMsg msg = monitor.getMonitorMessage(); System.out.printf("%s %s%n", msg.command(), msg.args());}import asynciofrom glide import GlideClientConfiguration, NodeAddressfrom glide.monitor_client import MonitorClient, MonitorMsg
async def main(): config = GlideClientConfiguration([NodeAddress("localhost", 6379)])
# Callback mode def on_monitor_msg(msg: MonitorMsg) -> None: print(f"{msg.timestamp:.6f} [{msg.db}] {msg.client_addr} {msg.command} {msg.args}")
async with await MonitorClient.create(config, callback=on_monitor_msg) as monitor: # Run commands on a separate client — the callback will print each one. await asyncio.sleep(5)
# Queue mode async with await MonitorClient.create(config) as monitor: msg = await monitor.get_monitor_message() print(f"{msg.command} {msg.args}")
asyncio.run(main())import { GlideMonitorClient, MonitorLine } from "@valkey/valkey-glide";
const addresses = [{ host: "localhost", port: 6379 }];
// Callback modeconst callbackMonitor = await GlideMonitorClient.create( { addresses }, (line: MonitorLine) => { console.log(`${line.timestamp} [${line.db}] ${line.clientAddr} ${line.command} ${line.args.join(" ")}`); },);await callbackMonitor.close();
// Queue modeconst queueMonitor = await GlideMonitorClient.create({ addresses });const line = await queueMonitor.getNextMessage();console.log(`${line.command} ${line.args.join(" ")}`);await queueMonitor.close();package main
import ( "fmt" "time"
"github.com/valkey-io/valkey-glide/go/v2" "github.com/valkey-io/valkey-glide/go/v2/config")
func main() { cfg := config.NewClientConfiguration(). WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})
// Callback mode callbackMonitor, err := glide.NewMonitorClient(cfg, func(line glide.MonitorLine) { fmt.Printf("%.6f [%d] %s %s %v\n", line.Timestamp, line.DB, line.ClientAddr, line.Command, line.Args) }) if err != nil { panic(err) } time.Sleep(5 * time.Second) callbackMonitor.Close()
// Queue mode queueMonitor, err := glide.NewMonitorClient(cfg, nil) if err != nil { panic(err) } defer queueMonitor.Close()
line, err := queueMonitor.GetMonitorMessage() if err != nil { panic(err) } fmt.Printf("%s %v\n", line.Command, line.Args)}$addresses = [['host' => 'localhost', 'port' => 6379]];
// Callback mode$callbackMonitor = new ValkeyGlideMonitor(addresses: $addresses);// Run commands on a separate client while this listener is active.$callbackMonitor->listen(function (ValkeyGlideMonitorLine $line) { printf( "%.6f [%d] %s %s %s\n", $line->timestamp, $line->db, $line->clientAddr, $line->command, implode(' ', $line->args) );
return true; // Stop after the first message.});$callbackMonitor->close();
// Queue mode$queueMonitor = new ValkeyGlideMonitor(addresses: $addresses);// Run commands on a separate client before waiting for the next message.$line = $queueMonitor->getMonitorMessage(timeout: 5.0);if ($line !== null) { printf("%s %s\n", $line->command, implode(' ', $line->args));}$queueMonitor->close();The C# client returns an IAsyncEnumerable
stream instead of providing separate callback and queue modes. Similar functionality to other clients can easily be implemented using
the stream directly - see examples below.
using System.Threading.Channels;using Valkey.Glide;
using var config = new MonitorConfig("localhost", 6379);
void OnMessage(MonitorMessage msg) => Console.WriteLine($"{msg.Timestamp:O} [{msg.Database}] {msg.ClientAddress} {msg.Command} {string.Join(" ", msg.Args)}");
// Callback using delegate.await using var callbackMonitor = await MonitorClient.CreateClient(config);
using var callbackCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));await foreach (var msg in callbackMonitor.GetMessagesAsync(callbackCts.Token)){ OnMessage(msg);}
// Queue using channel.await using var queueMonitor = await MonitorClient.CreateClient(config);
var queue = Channel.CreateUnbounded<MonitorMessage>();using var queueCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));_ = Task.Run(async () =>{ await foreach (var msg in queueMonitor.GetMessagesAsync(queueCts.Token)) { await queue.Writer.WriteAsync(msg, queueCts.Token); } queue.Writer.Complete();});
var next = await queue.Reader.ReadAsync(queueCts.Token);OnMessage(next);Monitor Message Fields
Section titled “Monitor Message Fields”Each monitor message contains the following fields:
| Field | Type | Description |
|---|---|---|
| Timestamp | Floating point | Time when the command was processed |
| Database | Integer | Database index the command ran against |
| Client address | String | Address of the client that issued the command |
| Command | String | Command name |
| Arguments | List | Command arguments |
The exact names and types vary by client, following each language’s specifications and conventions.