Callback for ODBC Connection-level Tracing
ODBC applications provide a callback to receive trace messages for a particular connection.
Use the following prototype to implement a callback:
typedef void (*ODBC_TraceCallback) (const char *category, int level, const char *message, size_t size, void *context);
A callback is provided by setting the following connection attributes:
-
SQL_ATTR_TRACE_CALLBACK
-
(Optional) SQL_ATTR_TRACE_CALLBACK_CONTEXT
-
SQL_ATTR_TRACE_CALLBACK_OPTIONS
The context parameter provided by the attribute SQL_ATTR_TRACE_CALLBACK_CONTEXT goes back as the context parameter to the trace callback by the ODBC driver.
The client calls the callback once for each trace message and blocks until the callback returns.
The category parameter passed to the callback is a string representing the trace category of the message. The ODBC_TRACE_LEVEL parameter is an integer representing the severity level of the message with the following pre-defined values:
enum ODBC_TraceLevel {
ODBC_TRACE_LEVEL_NONE = 0x0,
ODBC_TRACE_LEVEL_FATAL = 0x1,
ODBC_TRACE_LEVEL_ERROR = 0x2,
ODBC_TRACE_LEVEL_WARNING = 0x3,
ODBC_TRACE_LEVEL_INFO = 0x4,
ODBC_TRACE_LEVEL_DEBUG = 0xF
};
Enable Multiple Trace Categories
Calling SQLSetConnectAttr() multiple times for an attribute replaces the previous value with the new value. For example, passing DEBUG for the options in one call and then API in a second call will not turn on both DEBUG and API tracing, but will disable DEBUG tracing and enable only API tracing. To enable multiple trace categories, provide all of them in a single trace option string:
SQLSetConnectAttr(hdbc, SQL_ATTR_TRACE_CALLBACK_OPTIONS, "DEBUG,API,SQL", SQL_NTS);
Example
The following example shows how to set up a connection trace callback:
static void MyDBConnection::traceCallback(const char *category, int level, const char *message, size_t size, void *context)
{
static_cast<MyDBConnection*>(context)->log(message, size);
}
void MyDBConnection::connect()
{
SQLAllocHandle(SQL_HANDLE_DBC, m_henv, &m_hdbc);
const char *traceOptions = "DEBUG,API,SQL";
SQLSetConnectAttr(m_hdbc, SQL_ATTR_TRACE_CALLBACK, (SQLPOINTER)traceCallback, 0);
SQLSetConnectAttr(m_hdbc, SQL_ATTR_TRACE_CALLBACK_CONTEXT, (SQLPOINTER)this, 0);
SQLSetConnectAttr(m_hdbc, SQL_ATTR_TRACE_CALLBACK_OPTIONS, (SQLPOINTER)traceOptions, SQL_NTS);
SQLDriverConnect(m_hdbc, ...)
}