TL;DR
Databricks job logs tend to hide in run output and on clusters that have already shut down. This guide sends them to the Elastic Stack with structured JSON, job and run IDs on every record, two ways to ship them, and a query for failures your logs never see. At 3 a.m., Kibana should hold answers, not an empty search box.
Three steps to read before the next outage:
Say a nightly Databricks job that builds the orders table fails at 3 a.m. The on-call engineer opens Kibana, where every other service’s logs live, and finds nothing. The job’s messages are in the run output and in the driver logs of a cluster that has already shut down. Working out what happened means clicking through the Databricks UI run by run.
The fix is to treat Databricks jobs like any other service and send their logs to the Elastic Stack. In practice that takes three pieces: write structured JSON logs from the job code, tag every record with the Databricks job ID and run ID, and ship the records to Elasticsearch, either directly from the job or through Databricks log delivery and an Elastic shipper. This guide shows each piece with Python code we ran, and adds a query on Databricks system tables to catch failures that never reach your own logging.
Key Takeaways
- Log in a structured format. The
ecs-loggingPython library turns standardloggingcalls into JSON that follows the Elastic Common Schema (ECS), which Kibana understands without custom parsing. - Pass
{{job.id}}and{{job.run_id}}into each task as parameters. Databricks replaces these dynamic value references at run time, and you add them to every log record. - Two ways to ship: send records straight to Elasticsearch with the Python client’s bulk helper, or let Databricks deliver cluster logs to storage and collect them with an Elastic shipper.
- When writing to a
logs-*-*data stream through the bulk API, use thecreateoperation. Data streams only accept new documents. - Your logs only show what your code reports. For job-level status (failed, timed out, cancelled), query
system.lakeflow.job_run_timeline.
What Is the Elastic Stack?
The Elastic Stack is a set of tools for collecting, storing, searching and visualizing data, most often logs. It used to be called the ELK Stack, after its first three parts:
- Elasticsearch stores and indexes the log records and answers search queries.
- Logstash is a processing pipeline that can parse and transform data on the way in.
- Kibana is the web interface for searching logs, building dashboards and setting alerts.
Elastic Agent and Beats such as Filebeat were added later to collect data from machines and files. You do not need all of them. A Python job can write straight to Elasticsearch, and Kibana reads from there.
Step 1: Write Structured Logs With ECS
Plain text logs like ERROR: failed to compute totals are hard to search across hundreds of runs. JSON logs with consistent field names are not. The Elastic Common Schema (ECS) is Elastic’s standard set of field names, such as log.level, error.type and event.dataset, and Elastic maintains a Python ECS logging library that plugs into the standard logging module.
pip install ecs-logging The script below sets up a logger with the ECS formatter, reads the job and run IDs from command-line arguments (more on those in step 2), and logs one normal message and one exception:
import argparse
import logging
import sys
import ecs_logging
parser = argparse.ArgumentParser()
parser.add_argument("--job-id", default="local")
parser.add_argument("--run-id", default="local")
args, _ = parser.parse_known_args()
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(ecs_logging.StdlibFormatter(exclude_fields=["process", "log.origin"]))
logger = logging.getLogger("orders_etl")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
# Fields added to every record, so you can filter by job and run in Kibana.
context = {"labels": {"databricks_job_id": args.job_id, "databricks_run_id": args.run_id}}
logger.info("Loaded source table", extra={**context, "event.dataset": "orders_etl", "rows": 18240})
try:
1 / 0
except ZeroDivisionError:
logger.exception("Failed to compute daily totals", extra=context) Running it locally with --job-id 6 --run-id 550315892394120 printed this as the first line (ecs-logging 2.3):
{"@timestamp":"2026-10-26T21:51:16.752Z","log.level":"info","message":"Loaded source table","ecs.version":"1.6.0","event":{"dataset":"orders_etl"},"labels":{"databricks_job_id":"6","databricks_run_id":"550315892394120"},"log":{"logger":"orders_etl","original":"Loaded source table"},"rows":18240} The second record carries error.type, error.message and error.stack_trace fields, filled in automatically by logger.exception. In Kibana you can now filter on labels.databricks_run_id to see one run, or on error.type to find every run that hit the same exception. ECS defines labels as a place for simple key-value tags, which suits IDs like these. Fields outside ECS, such as rows here, are allowed too.
Step 2: Pass the Job and Run IDs Into the Task
A log line is only useful if you can tie it to a run. Databricks Jobs support dynamic value references: placeholders in double curly braces that Databricks replaces with real values when the task starts. {{job.id}} becomes the job ID and {{job.run_id}} becomes the run ID.
For a Python script task, add them as task parameters:
["--job-id", "{{job.id}}", "--run-id", "{{job.run_id}}"] Two rules from the Databricks documentation matter here. References only work in parameters and fields that pass context into tasks, not inside the code itself. And a typo or missing brace is silently passed through as literal text, so check the first run’s logs to confirm the labels show real numbers rather than {{job.run_id}}.
Step 3: Ship the Logs to Elasticsearch
There are two practical routes. Pick based on who owns the cluster setup and how quickly you need logs to appear.
Option A: Send Directly From the Job
The job sends its own records to Elasticsearch with the official Python client. The handler below buffers ECS records and sends them in batches with helpers.bulk, then sends whatever is left when the job ends, even if it fails:
import json
import logging
import os
import ecs_logging
from elasticsearch import Elasticsearch, helpers
class ElasticBulkHandler(logging.Handler):
"""Buffer ECS-formatted log records and send them to Elasticsearch in bulk."""
def __init__(self, client, index, batch_size=500):
super().__init__()
self.client = client
self.index = index
self.batch_size = batch_size
self.buffer = []
self.setFormatter(ecs_logging.StdlibFormatter())
def emit(self, record):
self.buffer.append(json.loads(self.format(record)))
if len(self.buffer) >= self.batch_size:
self.flush()
def flush(self):
if not self.buffer:
return
actions = (
{"_op_type": "create", "_index": self.index, "_source": doc}
for doc in self.buffer
)
helpers.bulk(self.client, actions)
self.buffer = []
def close(self):
self.flush()
super().close()
client = Elasticsearch(os.environ["ES_URL"], api_key=os.environ["ES_API_KEY"])
handler = ElasticBulkHandler(client, index="logs-databricks.jobs-default")
logger = logging.getLogger("orders_etl")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
try:
logger.info("Job started")
# ... job code ...
logger.info("Job finished")
finally:
handler.close() # send whatever is left, even if the job fails We tested this with elasticsearch-py 9.5 against a local stub that accepts bulk requests. It sent one bulk request with both records as create operations. Two details are worth explaining:
- The index name follows the data stream naming scheme
logs-<dataset>-<namespace>. Elasticsearch has a built-in index template forlogs-*-*, so writing to this name creates a data stream with sensible log settings. Keep hyphens out of the dataset and namespace parts, since hyphens separate the three parts of the name. "_op_type": "create"is required because data streams are append-only. The default bulk operation,index, is rejected for data streams.
On Databricks, do not put the API key in the notebook or script. Store it with Databricks secrets management and read it at run time with dbutils.secrets.get(scope="logging", key="es-api-key"), using your own scope and key names. Create an Elasticsearch API key that can only write to logs-databricks.jobs-*.
Install the two libraries on the job’s compute (for example as job libraries): ecs-logging and elasticsearch. Pin their versions so a new release does not change behavior overnight.
Option B: Log Delivery Plus an Elastic Shipper
Databricks can deliver a cluster’s driver, worker and event logs to a storage location that you set in the compute configuration’s logging settings, in a folder per cluster ID. If your job writes ECS JSON to standard output, those lines end up in the delivered driver logs. An Elastic shipper, such as Elastic Agent or Filebeat, then reads the files and sends them to Elasticsearch.
A variation is to install the shipper on the cluster nodes with a cluster-scoped init script, so it reads log files as they are written. Yury Kalbaska’s walkthrough on logging Databricks workflows with the Elastic Stack uses Filebeat this way. Init scripts need permission to configure them on the cluster, and every node runs the script at startup, so keep it short and keep credentials out of its output.
Which Option Should You Choose?
| A: Direct from the job | B: Log delivery plus shipper | |
|---|---|---|
| Setup | Two Python libraries and an API key | Storage, log delivery settings and a shipper to run and maintain |
| What it captures | Only what your code logs | Everything in the cluster logs, including Spark and library messages |
| Delay | Each batch, or at job end | Depends on delivery and collection intervals |
| If the process crashes hard | Buffered records can be lost | Lines already written to the log file are kept |
| Best for | Teams that own the job code | Platform teams standardizing logging across many jobs |
Many teams start with option A for the jobs they care most about and move to option B once several teams need the same setup.
Step 4: Catch Failures Your Logs Never See
Application logs have a blind spot. If a job times out, is cancelled, or fails before your logging code runs, there may be no log record at all. Databricks records job runs in system tables, including system.lakeflow.job_run_timeline, described in the jobs system table reference. A query like this lists runs from the last seven days that did not succeed:
SELECT workspace_id, job_id, run_id, result_state,
period_start_time, period_end_time
FROM system.lakeflow.job_run_timeline
WHERE result_state IS NOT NULL
AND result_state != 'SUCCEEDED'
AND period_start_time >= current_date() - INTERVAL 7 DAYS
ORDER BY period_end_time DESC Join on both workspace_id and job_id, because a job ID is unique only within one workspace. Long runs are split into hourly rows, so the query keeps only rows that carry a result_state, the field that records how a run ended. You can schedule this query and send the results to Elasticsearch with the same bulk helper, so job status and application logs sit side by side in Kibana. System tables have to be enabled for your account, and the query was not run here.
Logs explain failures; checks prevent some of them. Validating input tables before the heavy work starts, for example with Pandera data validation, turns a vague failure deep in a job into a clear log record at the first step. And pinning job library versions, as covered in our explainer on requirements.txt vs pyproject.toml, removes a common cause of overnight surprises.
Back to the 3 A.M. Failure
With this setup, the on-call engineer from the opening opens Kibana, filters on labels.databricks_job_id, and sees the failed run’s records, including the exception type and stack trace, next to every other service’s logs. If the job died before logging anything, the system table query shows the run as failed or timed out. No clicking through runs on a cluster that no longer exists.
Frequently Asked Questions
Can Databricks Send Logs to Elasticsearch Natively?
Databricks does not write job logs to Elasticsearch on its own. It can deliver cluster logs to storage you configure, and from there an Elastic shipper can collect them. The other route is to send logs from your job code with the Elasticsearch Python client, as shown above.
Should I Use Logstash?
Only if you need to parse or transform logs on the way in, such as turning plain text lines into fields. If your job already writes ECS JSON, you can send it straight to Elasticsearch and skip Logstash.
Does print() Output Show Up in Elasticsearch?
Not with option A, which only sends records that go through the logger. With option B, anything written to standard output lands in the driver logs and can be collected, but plain print lines have no level, no timestamp field and no run ID. Use the logger instead.
How Do I Keep Elasticsearch Costs Under Control?
Log at INFO and above in production, drop fields you never search, and set a retention policy on the data stream so old logs are deleted automatically. The ECS formatter’s exclude_fields option, used in the first example, removes fields such as process details from every record.




