eXtremeDB Tracing Framework C API

The eXtremeDB tracing framework allows applications to output trace and debugging information to a log file. All C/C++ applications should link with the mcotrace library. The tracing framework supports synchronous and asynchronous delivery, configurable filtering, message formatting, file rotation, and bounded asynchronous queues.

Note that xSQL can also be configured to output trace information. Please refer to the xSQL Tracing Framework page for details.

For an overview, see the Tracing Framework page.

How to use

Before any database operations occur, a C/C++ application can call mco_trace_init_simple_handler() to enable tracing with a simple single-threaded handler. For example:

    ...
    rc = mco_db_connect( db_name, &db );
    if ( MCO_S_OK == rc )
    {
        char * trace_file = "Trace_Output.dbg";
        ...
        mco_trace_init_simple_handler(
            trace_file,
            MCO_TRACE_LEAVE_OPENED,
            "At %t in module %m, thread %i caused error %e from line %l of file %f");
        ...
    }

Alternatively, it is possible to provide a user-defined trace handler (also called an "appender" because it appends messages to an output file) that is called for every message triggered by a traced database operation. The user-defined handler is then registered by calling the mco_trace_set_handler() API. This call supersedes any existing trace handler.

    int my_trace_handler( mco_severity severity, mco_trace_module module,
                        const char *file, int line, const char *fmt, ... )
    {
        /* Trace handler implementation */

        return MCO_S_OK;
    }

    ...
    rc = mco_db_connect( db_name, &db );
    if ( MCO_S_OK == rc )
    {
        ...
        mco_trace_set_handler( my_trace_handler );
        ...
    }

Then, call mco_trace_set_modules_mask() to set the eXtremeDB modules for which trace output is desired and call mco_trace_set_level() to determine the granularity of trace messages. For example:

    ...
    rc = mco_db_connect( db_name, &db );
    if ( MCO_S_OK == rc )
    {
        ...
        mco_trace_set_modules_mask(
            1 << MCO_TRACE_TMGR |
            1 << MCO_TRACE_TL );
        mco_trace_set_level( MCO_TRACE_ERROR );
        ...
    }

Normalized Trace Record

A normalized mco_trace_message contains the information captured at the trace call site:

Process and thread identifiers use the SAL mco_process_t type rather than a trace-specific integer representation. The common formatter renders this opaque platform value with %p. Consequently, the public trace record does not assume a particular process or thread identifier width.

The asynchronous producer captures the timestamp, thread ID, and errno before queueing the record. The formatter therefore never substitutes values belonging to the asynchronous worker thread.

Message pointers passed to a handler are valid only for the duration of that callback. A handler that needs to retain message data must copy it.

The correctly spelled public asynchronous handler descriptor types are mco_async_trace_message_handler_desc_t and mco_async_trace_message_handler_desc_h. The historical hander spellings remain available as typedef aliases for source compatibility.

Common Format

The default trace format is:

    %t [%i] %m-%s-%f:%l-%e 

The default format includes the originating thread ID but does not include the process ID. Applications that require the process ID can explicitly include %p in the format.

Short Tokens

%t
UTC ISO 8601 timestamp with microseconds.
%d{format}
UTC timestamp formatted using strftime syntax.
%u
Six-digit microsecond fraction.
%p
Process ID.
%i
Originating thread ID.
%m
Trace module.
%s
Trace severity.
%r
Saved numeric errno value.
%R
Text corresponding to the saved errno value.
%f
Source file.
%l
Source line.
%e
Expanded trace message.
%%
Percent sign.

Named Tokens

The canonical named forms are:

    %{timestamp}
    %{timestamp:strftime-format}
    %{millis}
    %{micros}
    %{pid}
    %{thread}
    %{module}
    %{severity}
    %{errno}
    %{errstr}
    %{file}
    %{line}
    %{message} 

The short tokens retain their established simple and XSQL meanings. Conflicting legacy meanings from the direct asynchronous formatter are not preserved.

Common Configuration API

The common configuration API can configure a complete tracing handler, including delivery mode, destination, formatting, filtering, file lifecycle, rotation, and asynchronous queue behavior.

    mco_trace_config_t config;

    mco_trace_config_init( &config );

    config.mode = MCO_TRACE_DELIVERY_ASYNC;
    strcpy( config.filename, "application.trace" );
    strcpy( config.format, MCO_TRACE_DEFAULT_FORMAT );

    config.severity = MCO_TRACE_INFO;
    config.modules_mask = MCO_TRACE_MASK_ALL;
    config.options = MCO_TRACE_KEEP_CLOSED;

    config.start_policy = MCO_TRACE_FILE_APPEND;
    config.rotate_policy = MCO_TRACE_ROTATE_SIZE;
    config.rotate_size_bytes = 10 * 1024 * 1024;
    config.rotated_file_limit = 5;

    config.async_options.queue_capacity = 4096;
    config.async_options.overflow_policy =
        MCO_TRACE_QUEUE_DROP_NEWEST;

    rc = mco_trace_start_config( &config );

    /* Application work. */

    mco_trace_stop_config();

mco_trace_start_config() configures one built-in file handler. Applications that require multiple outputs can use mco_trace_init_ex() and register multiple descriptors with mco_trace_add_async_handler().

For a low-level mco_trace_file_appender_t, a non-NULL format pointer is borrowed and must remain valid until the handler has stopped. The common configuration API instead copies its fixed-size format field into configuration-owned storage before starting the asynchronous handler.

The existing mco_trace_init_simple_handler(), mco_trace_init(), and low-level file-appender APIs remain available.

File Lifecycle

The following startup policies are available:

MCO_TRACE_FILE_APPEND
Preserve an existing trace file and append new records.
MCO_TRACE_FILE_TRUNCATE
Start a non-rotating file empty.
MCO_TRACE_FILE_ROTATE_EXISTING
Rename an existing base file before writing the first record.

MCO_TRACE_FILE_APPEND is the default. When size or time rotation is enabled, an existing base file is rotated at application startup even when the explicit start policy is append. This gives each application run a new base file.

Reapplying a configuration for the same file in one process does not perform startup rotation again. Likewise, an idempotent repeated mco_runtime_start() returns before trace initialization and leaves the active environment-configured handler untouched.

Rotated files use the base_N naming convention. A nonzero rotated_file_limit removes the oldest numbered files after rotation. A value of zero means unlimited retention.

Rotation limits are soft by record. Time rotation occurs when a subsequent record observes that the configured period has elapsed.

stderr is supported in both delivery modes when rotation is disabled. Combining stderr with size or time rotation, or with ROTATE_EXISTING, is rejected as an invalid configuration.

Asynchronous Queue

mco_trace_init() uses a bounded queue with a capacity of 4096 records and the MCO_TRACE_QUEUE_DROP_NEWEST overflow policy.

The extended initializer allows the queue capacity and overflow policy to be configured:

    mco_trace_async_options_t options;

    options.queue_capacity = 1024;
    options.overflow_policy = MCO_TRACE_QUEUE_BLOCK;

    rc = mco_trace_init_ex( &options );
            

A queue capacity of zero requests the historical unbounded queue.

Overflow Policies

MCO_TRACE_QUEUE_DROP_NEWEST
Discard the incoming record when the queue is full.
MCO_TRACE_QUEUE_DROP_OLDEST
Remove the oldest queued record and enqueue the incoming record.
MCO_TRACE_QUEUE_BLOCK
Wait until the worker frees queue space.

mco_trace_get_dropped_messages() returns the current number of dropped messages while tracing is active and the final count after tracing has stopped.

Environment Variables

Activation and Defaults

The automatic environment-configured handler is disabled when no MCO_TRACE* variable is present. If any recognized variable is present, runtime startup creates one process-local handler and uses the defaults below for every field that was not explicitly overridden.

For example, setting only MCO_TRACE_FILE=application.trace enables synchronous NOTICE tracing to that file.

Set the environment variables before the first mco_runtime_start(). An idempotent repeated mco_runtime_start() does not reread them. A later start after a complete runtime stop reads them again.

Variable
Accepted values / default / meaning
MCO_TRACE

Accepted values: fatal, error, warning, notice, info, debug, verbose.

Default: unset. This is a legacy severity/activation variable; it is not a Boolean.

MCO_TRACE_LEVEL

Accepted values: the same severity names as MCO_TRACE.

Default: notice. This is the maximum verbosity emitted. If both level variables exist, this variable wins.

MCO_TRACE_FILE

Accepted value: a path or stderr.

Default: stderr. Relative paths are relative to the process working directory.

MCO_TRACE_FORMAT

Accepted value: a common trace format string.

Default: %t [%i] %m-%s-%f:%l-%e.

MCO_TRACE_MODULE

Accepted value: one or more module names.

Separators are space, comma, semicolon, and vertical bar. Default: all modules.

MCO_TRACE_MODE

Accepted values: sync, async.

Default: sync, unless asynchronous mode is inferred from another setting.

MCO_TRACE_FILE_OPTIONS

Accepted values: leave_opened, keep_closed.

Default: keep_closed.

MCO_TRACE_FILE_START

Accepted values: append, truncate, rotate_existing.

Default: append.

MCO_TRACE_ROTATE_POLICY

Accepted values: none/no, size, time.

Default: none. Size and time rotation require asynchronous delivery.

MCO_TRACE_ROTATE_SIZE

Accepted value: positive decimal byte count.

Default: 1048576. This is a soft size threshold; rotation occurs between complete records.

MCO_TRACE_ROTATE_PERIOD

Accepted value: positive decimal number of seconds.

Default: 86400. Rotation occurs when a later record is written after the period has elapsed.

MCO_TRACE_ROTATE_FILES

Accepted value: nonnegative decimal count.

Default: 0. Zero means unlimited retention.

MCO_TRACE_QUEUE_CAPACITY

Accepted value: nonnegative decimal record count.

Default: 4096. Zero selects the historical unbounded queue.

MCO_TRACE_QUEUE_OVERFLOW

Accepted values: drop_newest, drop_oldest, block.

Default: drop_newest.

Severity and enum values are case-insensitive. Selecting debug, for example, emits FATAL through DEBUG and excludes VERBOSE.

Numeric variables accept only plain decimal digits. Suffixes such as 1m, signs, spaces, and empty values are invalid. To disable automatic environment tracing, remove all recognized variables rather than assigning an empty value.

Supported Modules

The following module names are supported:


BSE LAYOUT ORDER DISK TMGR CONN DBINST ALLOCATOR INDEX BTREE KDTREE PTREE
RTREE HNSW TRIGRAM HASH PATTERN CRYPT ZIP CURSOR WRAPPER XML BLOB DDL SQL
RSQL TL SEQ FILE SYNC BACKUP HA CLUSTER ODBC PYTHON LUA JNI SAL NETWORK
SHMEM TRACE PERF UDA XSQL IOT TRANSCHECK TRANSLOG JSER 

Module names are case-insensitive. There is no special all token. Leave MCO_TRACE_MODULE unset to enable all modules.

Sync and Async Selection

Asynchronous mode is selected when MCO_TRACE_MODE=async is specified explicitly. When the mode is absent, it is inferred only by one of the following:

The numeric rotation threshold, period, or retention variables alone merely change dormant configuration fields. They do not enable rotation or infer asynchronous mode.

Explicit MCO_TRACE_MODE=sync combined with an asynchronous-only setting is rejected rather than silently ignoring the setting.

truncate is valid without rotation. rotate_existing and size/time rotation require asynchronous mode. Any enabled size/time rotation policy also rotates an existing base file at process startup, even when the start policy remains append.

Rotated files are named base_1, base_2, and so on.

If the product was built with MCO_TRACE_ASYNC_TRACE=0, requesting asynchronous mode returns MCO_E_UNSUPPORTED. Rotation also requires the compiled file-rotation support. File tracing requires a filesystem-capable target.

Validation and Process Scope

Environment application is transactional. An invalid value does not leave a partially modified configuration.

During normal runtime initialization, an invalid combination is returned by mco_runtime_start() as MCO_E_ILLEGAL_PARAM. An unavailable compiled feature returns MCO_E_UNSUPPORTED.

Failure to open a destination while writing is reported as TRACE-ERROR, and the handler falls back to stderr.

The environment creates exactly one handler per process. The queue, file handle, filtering, and rotation state are process-local and are not stored in the shared-memory registry.

Independent processes are not coordinated when they write or rotate the same path. Applications that require multiple handlers or destinations must use the explicit C API.

XSQL first creates configuration from trace_params and then overlays only the environment fields that are present. The same validation and mode rules apply.

Environment Variable Examples

Synchronous Debug Tracing for Selected SQL Modules

    MCO_TRACE_LEVEL=debug
    MCO_TRACE_FILE=application.trace
    MCO_TRACE_MODULE=SQL,RSQL,XSQL
    MCO_TRACE_FORMAT=%t [%i] %m %s: %e 

Asynchronous Tracing with Size Rotation and Bounded Retention

    MCO_TRACE_MODE=async
    MCO_TRACE_LEVEL=info
    MCO_TRACE_FILE=application.trace
    MCO_TRACE_ROTATE_POLICY=size
    MCO_TRACE_ROTATE_SIZE=10485760
    MCO_TRACE_ROTATE_FILES=5
    MCO_TRACE_QUEUE_CAPACITY=4096
    MCO_TRACE_QUEUE_OVERFLOW=drop_newest