Persist custom model serving data to Unity Catalog

Use endpoint telemetry to persist OpenTelemetry logs, traces, and metrics from your custom model and agent serving endpoints to Unity Catalog tables, then query them with SQL for root cause analysis, endpoint health, and compliance requirements. This page covers endpoint telemetry but not request and response payloads (see inference tables) or the build and service logs in the Logs tab (see Monitor Model Serving endpoints).

Requirements

  • Your workspace must be enabled for Unity Catalog. Default storage is not supported.

  • You must have USE CATALOG, USE SCHEMA, CREATE TABLE, and MODIFY permissions on the destination Unity Catalog catalog and schema where the logs are stored.

  • An existing custom model serving endpoint or agent serving endpoint, or permissions to create one.

  • Your workspace must be in a supported region:

    • canadacentral
    • westus
    • westus2
    • southcentralus
    • eastus
    • eastus2
    • centralus
    • northcentralus
    • swedencentral
    • westeurope
    • northeurope
    • uksouth
    • australiaeast
    • southeastasia

Step 1: Instrument your model code

Add instrumentation to your model code to capture telemetry. In the samples, <prefix> is the table prefix that you set when you enable endpoint telemetry, or the endpoint name if you leave it blank.

  1. Add application logging to your model. Use Python logging instead of print. Endpoint telemetry automatically captures Python logging output at WARNING and above. It doesn't capture print output, except on custom LLM endpoints. No OpenTelemetry SDK instrumentation is required for basic logging.

    import logging
    
    import mlflow
    
    
    class MyCustomModel(mlflow.pyfunc.PythonModel):
        def predict(self, context, model_input):
            # This log will be persisted to the <prefix>_otel_logs table
            logging.warning("Received inference request")
    
            try:
                # Your model logic here
                result = model_input * 2
                return result
            except Exception as e:
                # Error logs are also captured with severity 'ERROR'
                logging.error(f"Inference failed: {e}")
                raise e
    

    The root logging level is set to WARNING. See Troubleshooting to change the logging level.

  2. (Optional) Instrument custom metrics and traces with OpenTelemetry. To capture custom metrics and traces beyond basic logging, add OpenTelemetry SDK instrumentation to your model. Expand the following section for a complete example that shows how to create counters, record spans, and attach custom attributes.

    Brackets square icon. Example: Custom metrics, spans, and model logging with OpenTelemetry

    Note

    Due to limitations in model serialization, you must write your model to a separate file before logging to avoid errors, as shown below using %%writefile return_input_model.py. Outside a notebook, save the same code to that file yourself.

    %%writefile return_input_model.py
    import os
    
    import mlflow
    from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
    from opentelemetry.metrics import get_meter, set_meter_provider
    from opentelemetry.sdk.metrics import MeterProvider
    from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
    from opentelemetry.sdk.resources import Resource
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor
    from opentelemetry.trace import get_tracer, set_tracer_provider
    
    # highlight-start
    # ---- OTel initialization (per-worker) ----
    resource = Resource.create({
        "worker.pid": str(os.getpid()),
    })
    
    otlp_trace_exporter = OTLPSpanExporter()
    tracer_provider = TracerProvider(resource=resource)
    tracer_provider.add_span_processor(BatchSpanProcessor(otlp_trace_exporter))
    set_tracer_provider(tracer_provider)
    
    otlp_metric_exporter = OTLPMetricExporter()
    metric_reader = PeriodicExportingMetricReader(otlp_metric_exporter)
    meter_provider = MeterProvider(metric_readers=[metric_reader], resource=resource)
    set_meter_provider(meter_provider)
    
    _tracer = get_tracer(__name__)
    _meter = get_meter(__name__)
    _prediction_counter = _meter.create_counter(
        name="prediction_count",
        description="Number of predictions made",
        unit="1"
    )
    # highlight-end
    
    
    class ReturnInputModel(mlflow.pyfunc.PythonModel):
        def load_context(self, context):
            # highlight-start
            self.tracer = _tracer
            self.prediction_counter = _prediction_counter
            # highlight-end
    
        def predict(self, context, model_input):
            # highlight-next-line
            with self.tracer.start_as_current_span("ReturnInputModel.predict") as span:
                # highlight-next-line
                span.set_attribute("input_shape", str(model_input.shape))
                # highlight-next-line
                span.set_attribute("input_columns", str(list(model_input.columns)))
                # highlight-next-line
                self.prediction_counter.add(1)
                return model_input
    
    mlflow.models.set_model(ReturnInputModel())
    
  3. (Optional) Log custom per-request data. To persist your own data for each request, such as intermediate scores, emit one OpenTelemetry log record per request. The record is stored as one row in the <prefix>_otel_logs table.

    The OpenTelemetry exporter sends each record over HTTP to the telemetry collector in the endpoint's pod, which delivers it to Unity Catalog outside your model process. The endpoint sets OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_PROTOCOL (http/protobuf) for your model container, so the exporter needs no configuration. Use the HTTP exporter, not the gRPC exporter.

    import json
    
    import mlflow
    from opentelemetry._logs import LogRecord
    from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
    from opentelemetry.sdk._logs import LoggerProvider
    from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
    
    logger_provider = LoggerProvider()
    logger_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter()))
    _record_logger = logger_provider.get_logger(__name__)
    
    
    class MyCustomModel(mlflow.pyfunc.PythonModel):
        def predict(self, context, model_input):
            scores = {"model_score": 0.82, "lookup_hits": 3}
    
            # A JSON string body is much cheaper to encode than a nested dict
            _record_logger.emit(
                LogRecord(
                    event_name="prediction_details",
                    body=json.dumps(scores),
                    attributes={"model_version": "1"},
                )
            )
            return model_input
    

    To read the records, filter on event_name:

    SELECT time, body, attributes
    FROM <catalog>.<schema>.<prefix>_otel_logs
    WHERE event_name = 'prediction_details';
    

    For per-request data, don't call an ingestion SDK, such as the Zerobus Ingest SDK, from your model code. If the service is slow or unavailable, those calls can block your model. With OpenTelemetry, your model only hands the record to the local collector, so a slow or unavailable ingestion service delays delivery but doesn't block requests. Also avoid Python logging for records you emit on every request.

  4. Log and register the model.

    The code below logs return_input_model.py, the file that the optional example above creates. If you skipped that example, create the file with the same code first.

    import pandas as pd
    import mlflow
    from mlflow.models import infer_signature
    
    # Prepare tabular input/output for signature (pyfunc expects DataFrame)
    input_df = pd.DataFrame({"inputs": ["hello world"]})
    output_df = input_df.copy()  # model returns input unchanged
    
    # Log the model with OpenTelemetry dependencies (using code-based logging to avoid serialization issues)
    with mlflow.start_run():
        signature = infer_signature(input_df, output_df)
    
        model_info = mlflow.pyfunc.log_model(
            name="model",
            python_model="return_input_model.py",
            signature=signature,
            input_example=input_df,
            pip_requirements=[
                "mlflow==3.1",
                # highlight-next-line
                "opentelemetry-sdk>=1.37.0",
                # highlight-next-line
                "opentelemetry-exporter-otlp-proto-http>=1.37.0",
            ],
        )
    
    # Use Unity Catalog name: catalog.schema.model_name
    MODEL_NAME = "catalog.schema.model_name"
    registered = mlflow.register_model(
        model_info.model_uri,
        MODEL_NAME,
    )
    

    The register_model call returns a ModelVersion object for the new model version, and the registered variable holds it.

Step 2: Prepare the Unity Catalog destination

Before creating your endpoint, ensure you have a catalog and schema ready to receive the telemetry data. Azure Databricks automatically creates the necessary tables in this schema if they do not already exist.

  1. In Catalog Explorer, select the catalog and schema you want to use, for example, my_catalog.observability.

  2. If you don't already have a destination schema or catalog, create a schema or create a catalog to hold the telemetry tables. For example:

    CREATE CATALOG IF NOT EXISTS my_catalog;
    CREATE SCHEMA IF NOT EXISTS my_catalog.observability;
    
  3. Make sure the identity enabling telemetry has the USE CATALOG, USE SCHEMA, CREATE TABLE, and MODIFY privileges on the destination catalog and schema. These privileges are required so that Azure Databricks can automatically create and write to the telemetry tables. You can also, grant the privileges, for example:

    GRANT USE CATALOG ON CATALOG my_catalog TO `<principal>`;
    GRANT USE SCHEMA, CREATE TABLE, MODIFY ON SCHEMA my_catalog.observability TO `<principal>`;
    

Step 3: Enable endpoint telemetry

You can enable telemetry when creating a new endpoint or add it to an existing one.

On a new endpoint

To enable telemetry when you create the endpoint:

  1. In the left sidebar, select Serving.
  2. Select Create serving endpoint.
  3. Expand Advanced options, go to the AI Gateway section, and select Enable inference tables and telemetry.
  4. Unity Catalog location: Select the destination Catalog and Schema prepared in step 2.
  5. (Optional) Table prefix: Enter a prefix for the generated tables. If you leave it blank, the endpoint name is the prefix. The tables are named <prefix>_otel_logs, <prefix>_otel_spans, and <prefix>_otel_metrics.
  6. Complete the rest of the endpoint configuration (Model selection, Compute settings) and select Create.

To do this with the API:

Brackets square icon. Enable telemetry using the API
curl -X POST -H "Authorization: Bearer <your-token>" \
https://<workspace-url>/api/2.0/serving-endpoints \
-d '{
  "name": "my-custom-logging-endpoint",
  "config": {
    "served_entities": [
      {
        "name": "my-model",
        "entity_name": "my-model",
        "entity_version": "1",
        "workload_size": "Small",
        "scale_to_zero_enabled": true
      }
    ]
  },
  "telemetry_config": {
    "table_names": {
      "logs_table": "my_catalog.observability.custom_endpoint_logs",
      "metrics_table": "my_catalog.observability.custom_endpoint_metrics",
      "traces_table": "my_catalog.observability.custom_endpoint_spans"
    },
    "inference_table_config": {
      "sampling_fraction": 0.1
    }
  }
}'

inference_table_config.sampling_fraction is optional and controls the fraction of requests logged to the inference table. It takes a value between 0 and 1, and the default is 1, which logs all requests. Include table_names when you first configure inference tables. To change only the sampling rate on an endpoint that already has them, send inference_table_config without table_names. For details on sampling behavior, see Payload sampling.

On an existing endpoint

Note

Updating triggers a new deployment. Changes take effect once the deployment completes.

To enable telemetry on the endpoint view page:

  1. From the endpoint view page, in the AI Gateway section, click Edit AI Gateway, then select Enable inference tables and telemetry.
  2. Unity Catalog location: Select the destination Catalog and Schema prepared in step 2.
  3. (Optional) Table prefix: Enter a prefix for the generated tables. If you leave it blank, the endpoint name is the prefix. The tables are named <prefix>_otel_logs, <prefix>_otel_spans, and <prefix>_otel_metrics.
  4. Select Update.

Step 4: Verify and query telemetry data

After the endpoint receives traffic, telemetry data streams to the configured Unity Catalog tables.

  1. Open Catalog Explorer or the SQL Editor.

  2. Locate the table named <prefix>_otel_logs in your configured schema.

  3. Run a query to verify data is flowing:

    SELECT * FROM <catalog>.<schema>.<prefix>_otel_logs
    LIMIT 10;
    

    If the query returns no rows, see Troubleshooting.

Query telemetry data

The following examples show common queries.

To view the full schema of any telemetry table, run:

DESCRIBE TABLE <catalog>.<schema>.<prefix>_otel_logs;

Use these columns to filter and correlate telemetry data:

  • time: the record's timestamp in UTC, derived from the OpenTelemetry time_unix_nano field.
  • severity_text
  • body
  • trace_id
  • span_id
  • attributes: a VARIANT value that contains event-specific metadata.

Note

Tables that an earlier version of endpoint telemetry created might have time_unix_nano and no time column. Run the DESCRIBE TABLE command above to check whether your table has a time column. In those tables, time_unix_nano is the event time in nanoseconds since the Unix epoch. Use timestamp_micros(coalesce(time_unix_nano, observed_time_unix_nano) DIV 1000) in place of time.

Check for errors in the last hour

SELECT
  time,
  severity_text,
  body,
  attributes
FROM <catalog>.<schema>.<prefix>_otel_logs
WHERE
  severity_text = 'ERROR'
  AND time > current_timestamp() - INTERVAL 1 HOUR
ORDER BY time DESC;

Troubleshooting

INFO and DEBUG logs don't appear in the table

The root logging level defaults to WARNING to reduce overhead. Logs below that level, such as INFO and DEBUG, aren't captured.

To capture them, set a lower level in your model's load_context method. The following example sets the root logger and its handlers to DEBUG:

import logging

import mlflow


class MyModel(mlflow.pyfunc.PythonModel):
    def load_context(self, context):
        root = logging.getLogger()
        root.setLevel(logging.DEBUG)
        for handler in root.handlers:
            handler.setLevel(logging.DEBUG)

The change is part of your model code, so log a new model version and update the endpoint to serve it. See Update an endpoint's configuration.

Limitations

The following limits apply to endpoint telemetry:

  • Schema evolution on the target table is not supported.
  • Only managed Delta tables are supported. External storage and default storage are not supported.
  • The table location must be in the same region as your workspace.
  • Only table names with ASCII letters, digits, and underscores are supported.
  • Recreating a target table is not supported.
  • Only single availability zone (single-az) durability is supported.
  • Delivery is at-least-once. An acknowledgement from the server means the record is durable and in the Delta table.
  • A record can appear more than one time in the table.
  • Records must be less than 10 MiB each.
  • Telemetry requests must be less than 30 MiB each. This limit is separate from the payload limit for inference requests to the endpoint. See Resource and payload limits.
  • Log lines must be less than 1 MB each.
  • Telemetry latency degrades beyond 2500 QPS.
  • Logs appear in the Unity Catalog table a few seconds after they are emitted.

Additional resources

Resource Description
Monitor Model Serving endpoints Compare the monitoring tools for Model Serving endpoints.
Log requests and responses for serving endpoints (legacy) Log request and response payloads to Unity Catalog tables.