Thursday, April 03, 2008

MySQL Proxy Recipes - Debugging messages on demand

MySQL Proxy, in addition to dealing with the packets sent between client and server, can optionally send text messages to the terminal window where it was launched. These messages, using the built-in function print(), can be very useful when you develop an application, because can give you information on what is going on. However, when the script is well tuned, all these messages can be distracting and even annoying.
OTOH, if you plan to extend the development of the script, leaving the telling messages in place can be very useful. One handy solution is to include conditional print messages, controlled by an environment variable.
  1. Change all occurrences of print to print_debug;
  2. Create a function print_debug that will print the message depending on the value of a local variable DEBUG;
  3. At the start of the script, initialize the DEBUG variable from the environment.
local DEBUG = os.getenv('DEBUG') or 0

function read_query (packet )
if packet:byte() ~= proxy.COM_QUERY then return end
print_debug('inside read_query', 2)

function print_debug(msg, level)
level = level or 1
if DEBUG >= level then
print (msg)
print_debug accepts two parameters. The second one is optional and defaults to 1. If the global DEBUG variable is equal or higher than the level parameter, the message is printed. With this usage, you can define messages that will be printed only if the debug level is 2 or more, and others that will be printed when the level is 1. If you don't set the DEBUG variable, no messages will be printed. For example:
DEBUG=1 /usr/local/sbin/mysql-proxy --proxy-lua-script=simple_messages.lua
When the proxy is started in this way, you will get the queries (level 1). If you change DEBUG=1 into DEBUG=2, you will also see the "inside read_query" messages.
This technique can be tweaked and hacked to get more interesting results. For example, you can get conditional messages without changing the function name, or you can change the verbosity level at run time. These goodies will come to you - guess when? - during the tutorial mentioned below.

This post is part of a set of recipes that will eventually become a long article.
Want to hear more? Attend MySQL Proxy - The complete tutorial at the MySQL Users Conference 2008.

No comments:

Vote on Planet MySQL