When building a system, knowing what’s important to record can be difficult. Do you
record every time someone logs in? What about when they log out? Do you log every
time someone changes their account information? Or do you only log errors and
exceptions? I can’t answer those questions for you directly, but I can offer a method of keeping a recent list of log messages in Redis, which will let you get a snapshot view of your logs at any time.
To keep a recent list of logs, we’ll LPUSH log messages to a LIST and then trim that
LIST to a fixed size. Later, if we want to read the log messages, we can perform a simple
LRANGE to fetch the messages. We’ll take a few extra steps to support different
named log message queues and to support the typical log severity levels, but you can
remove either of those in your own code if you need to. The code for writing recent
logs to Redis is shown in the next listing.
Aside from the part that handles turning the different log levels into useful strings like
info and debug, the log_recent() function is simple—a quick LPUSH followed by an
LTRIM. Now that you have a better idea of what’s going on right now, can we discover
the most common (and maybe the most important) messages?
TRY REDIS ENTERPRISE CLOUD FREE
Redis Enterprise Cloud provides complete automation of day-to-day database operations. Start now with 30MB of free storage.
© 2021 Redis Labs. Redis and the cube logo are registered trademarks of Redis Labs Ltd.