Use an atomic global variable to control the switch to log query. And the query is logged before execution.
sessionVars
stats()