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.
- Change all occurrences of print to print_debug;
- Create a function print_debug that will print the message depending on the value of a local variable DEBUG;
- At the start of the script, initialize the DEBUG variable from the environment.
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:
local DEBUG = os.getenv('DEBUG') or 0
DEBUG = DEBUG + 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
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.
DEBUG=1 /usr/local/sbin/mysql-proxy --proxy-lua-script=simple_messages.lua
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.