Python for Data Engineers Interview Questions and Answers Part 7 - Error Handling, Logging and Reliable Pipelines

Python Interview Q&A · Part 7 of 10

In this post we are going to cover error handling, logging and reliable pipelines in Python for data engineers: except pass, custom exceptions, exception chaining, logging, idempotent reruns and configuration per environment. These are 7 real Python interview questions, asked the way they come up on a real project, and the last one is a scenario where the 2 AM job failed and nobody knew why until noon.

A pipeline that fails is normal. A pipeline that fails quietly, or loads half the data, or doubles it on a rerun, is the real problem. Interviewers ask about this because it separates a script that works on a good day from a job you can run in production: one that fails loudly, says why, and can be rerun safely.

Every Python step below runs on the sample data, and the output under each step is the real result.

Part 7 of the Real Time Python for Data Engineers Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Catch only the errors you can handle, keep the rejected rows, and fail loudly with custom exceptions and a non-zero exit code. Chain errors with raise ... from, configure logging once at the entry point and use logger.exception, make every run idempotent, keep settings per environment outside the code, and ship structured logs with a run ID.

Keep that in mind. Every question below is one piece of it.

Let's create some sample data

The setup is small. It clears two environment variables, writes one TOML config file each for dev and prod, and defines read_source, which stands in for the real source system: it yields three rows, and it can drop the connection at a given row.

Sample data - Python
import os
from pathlib import Path

# Q6: start from a clean environment, and write one small config file per environment
os.environ.pop("PIPELINE_ENV", None)
os.environ.pop("DB_PASSWORD", None)
Path("config").mkdir()
Path("config/dev.toml").write_text('db_host = "localhost"\nbatch_size = 500\n', encoding="utf-8")
Path("config/prod.toml").write_text('db_host = "sql-prod.internal"\nbatch_size = 5000\n', encoding="utf-8")

# Q5: stands in for the real source system. It yields rows and can drop the connection at a given row.
SOURCE_ROWS = ["A,5", "B,7", "C,2"]


def read_source(fail_at=None):
    for i, row in enumerate(SOURCE_ROWS):
        if i == fail_at:
            raise ConnectionError(f"source dropped at row {i + 1}")
        yield row

Question 1: A script wraps everything in try and except pass, and bad data goes through silently. What is wrong with it?

except: pass throws the error away. The job finishes, the scheduler shows success, and nobody knows rows were dropped. A bare except is worse: it also catches KeyboardInterrupt.

Let's see it. Here are three order rows, and the second quantity is the text "n/a". The loader converts each one with int, inside try, except, pass.

Python - The bad loader: try, bare except, pass
rows = [(1, "5"), (2, "n/a"), (3, "2")]   # (id, qty)

def load_bad(rows):
    loaded = []
    for row_id, qty in rows:
        try:
            loaded.append((row_id, int(qty)))
        except:
            pass
    return loaded

print(load_bad(rows))
Output
[(1, 5), (3, 2)]

Two rows come back: [(1, 5), (3, 2)]. Row 2 is gone, with no message.

The fix: catch only the errors you expect, here ValueError, and keep each rejected row with its reason. Let's run the same rows through that version.

Python - Catch only the expected errors and keep the rejected rows
def load(rows):
    good, rejected = [], []
    for row_id, qty in rows:
        try:
            good.append((row_id, int(qty)))
        except ValueError as e:
            rejected.append((row_id, str(e)))
    return good, rejected

good, rejected = load(rows)
print(f"loaded {len(good)}, rejected {len(rejected)}")
print(*rejected, sep="\n")
Output
loaded 2, rejected 1
(2, "invalid literal for int() with base 10: 'n/a'")

Now it says loaded 2, rejected 1: row 2, invalid literal for int() with base 10: 'n/a'.

Then decide on purpose what happens to the rejects:

  • Quarantine them, in a file or a table.
  • Log the count.
  • Fail the run when they pass a limit. That's the next question.
My rule

Never catch what you can't handle. Catch Exception only at the top of the job, to log the error and exit with a failure code.

Question 2: You need to stop the load when a business rule fails. How do you raise and use custom exceptions?

Create a small hierarchy: a PipelineError base class that inherits from Exception, and specific errors under it, like DataQualityError. Callers can catch one error, or all of them through the base class. Later in this post we add a third one, SourceFileError, for a file we can't parse.

The rule check raises the error with a clear message. The limit is 5 percent.

Python - A custom exception hierarchy and a business rule that raises
class PipelineError(Exception):
    """Base class for every error this pipeline raises."""

class DataQualityError(PipelineError):
    """A business rule failed: stop the load."""

def check_reject_rate(loaded, rejected, limit=5.0):
    pct = 100 * rejected / (loaded + rejected)
    if pct > limit:
        raise DataQualityError(
            f"reject rate {pct:.1f}% > {limit}%")

This step prints nothing; it prepares the data for the next step.

Let's try a batch with 940 good rows and 60 rejects.

Python - The rule fails for a batch with 60 rejects in 1,000
check_reject_rate(loaded=940, rejected=60)
Output (expected error)
DataQualityError: reject rate 6.0% > 5.0%

DataQualityError: reject rate 6.0% > 5.0%.

The entry point catches it: except DataQualityError, print why, and return exit code 1. The else branch runs only when nothing was raised, so the publish step stays out of the try block. Let's run it with 10 rejects in a thousand, and then with 60.

Python - The entry point catches the rule failure and returns an exit code
def run_job(loaded, rejected):
    try:
        check_reject_rate(loaded, rejected)
    except DataQualityError as e:
        print("load stopped:", e)
        return 1
    else:
        print("rule passed: publish the batch")
        return 0

print("exit code", run_job(990, 10))
print("exit code", run_job(940, 60))
Output
rule passed: publish the batch
exit code 0
load stopped: reject rate 6.0% > 5.0%
exit code 1

10 rejects: the rule passed, exit code 0. 60 rejects: the load stopped, exit code 1.

That non-zero exit code is what makes the scheduler mark the task failed.

Be specific

Raise specific errors, never a plain Exception, so the handler can tell a bad file from a dead database.

Question 3: An error message lost the original cause. How does exception chaining with raise from help?

The usual bug: code catches a low-level error and raises a new one with a vague message, like "load failed". Which file? Which row? What value? The real reason is buried.

vague_error.py
except ValueError:
    raise LoadError("load failed")

With raise ... from, the new error keeps the original as its cause. parse_qty catches the ValueError and raises a SourceFileError from it, with the file, the row and the bad value.

Python - Chain the low-level error with raise ... from
class SourceFileError(PipelineError):
    """A source file has a value we can't parse."""

def parse_qty(text, file, row):
    try:
        return int(text)
    except ValueError as e:
        msg = f"{file} row {row}: bad quantity {text!r}"
        raise SourceFileError(msg) from e

This step prints nothing; it prepares the data for the next step.

Now let's call it with a bad quantity and print both errors.

Python - The new error keeps the original as its __cause__
try:
    parse_qty("12x", "orders.csv", 3)
except SourceFileError as e:
    for exc in (e, e.__cause__):
        print(f"{type(exc).__name__}: {exc}")
Output
SourceFileError: orders.csv row 3: bad quantity '12x'
ValueError: invalid literal for int() with base 10: '12x'

The new error says orders.csv row 3: bad quantity '12x'. Its cause is the original ValueError: invalid literal for int() with base 10: '12x'. A full traceback prints both, joined by "The above exception was the direct cause of the following exception".

Without from, Python still keeps the first error as the context, but from says it on purpose. raise ... from None hides the original, so use it rarely.

Since Python 3.11, add_note attaches extra context, like the run ID, before you raise the error again.

add_note.py
except SourceFileError as e:
    e.add_note(f"run_id={run_id}")
    raise
Remember

A good error message answers three questions: which file, which row, what value.

Question 4: The team uses print statements to debug production jobs. How should logging be set up instead?

print has no levels, no logger names and one destination, and you can't turn it down without editing code. Logging gives you all of that.

printlogging
LEVELSnoneDEBUG, INFO, WARNING, ERROR, CRITICAL
DESTINATIONthe consolehandlers: stream, file, JSON for log tools
TURN IT DOWNedit the codechange the level

Configure it once, at the job's entry point, with basicConfig: level, stream and format. Each module gets its own logger with logging.getLogger(__name__), so the name follows the package, here etl.orders. Let's log one line at each of three levels.

Python - Configure logging once at the entry point
import logging
import sys

logging.basicConfig(
    level=logging.INFO, stream=sys.stdout,
    format="%(levelname)s %(name)s: %(message)s")
# in etl/orders.py this is logging.getLogger(__name__)
log = logging.getLogger("etl.orders")

log.debug("row detail, hidden at INFO")
log.info("loaded %s rows from %s", 940, "orders.csv")
log.warning("rejected %s rows", 60)
Output
INFO etl.orders: loaded 940 rows from orders.csv
WARNING etl.orders: rejected 60 rows

The debug line is hidden, because the level is INFO. INFO and WARNING come through with the level and the logger name. In production, add the timestamp; we leave it out so the output never changes.

Pass values as %s arguments, not an f-string, so formatting happens only when the message is logged. In an except block, call log.exception: it logs at ERROR level with the traceback, and the bare raise still fails the job. Let's try it on a bad quantity.

Python - logger.exception logs the traceback, then raise fails the job
for row_no, text in enumerate(["5", "12x"], start=1):
    try:
        qty = int(text)
    except ValueError:
        log.exception("bad quantity, row %s", row_no)
        raise
Output (expected error)
ERROR etl.orders: bad quantity, row 2
Traceback (most recent call last):
  File "load_orders.py", line 3, in <module>
ValueError: invalid literal for int() with base 10: '12x'
ValueError: invalid literal for int() with base 10: '12x'

The ERROR line for row 2 comes with the traceback, and then the ValueError still stops the run.

Two more rules:

  • A library adds only a NullHandler.
  • For Azure Monitor or Datadog, write JSON lines, which we build in the scenario.
Real-project tip

Configure logging in one place, the entry point. Every other module only calls getLogger(__name__).

Question 5: A job failed halfway and the rerun loaded duplicates. How do you make a Python pipeline idempotent?

Idempotent means a rerun with the same input gives the same result, never a double. The classic bug is append mode. read_source stands in for the real source, and tonight it drops the connection at row 3.

Python - The bug: append mode, and the first run fails at row 3
from pathlib import Path

def load_append(day, fail_at=None):
    with open("sales.csv", "a", encoding="utf-8") as f:
        for row in read_source(fail_at):
            f.write(f"{day},{row}\n")

try:
    load_append("2026-10-23", fail_at=2)
except ConnectionError as e:
    print("run 1 failed:", e)
Output
run 1 failed: source dropped at row 3

Run 1 appended A and B, then failed. Now let's rerun it and read the file.

Python - The rerun appends everything again
load_append("2026-10-23")                    # the rerun
print(Path("sales.csv").read_text(encoding="utf-8"), end="")
Output
2026-10-23,A,5
2026-10-23,B,7
2026-10-23,A,5
2026-10-23,B,7
2026-10-23,C,2

The rerun appended all three: 5 rows for 3 source rows.

The fix: write the day's slice to a hidden dot file in the same folder, which lake readers skip, and only when it's complete, replace the target with it. A rerun overwrites the same file. On POSIX, within one file system, the rename is atomic, so readers see the old file or the new one, never half.

Python - Idempotent: write the day to a temp file, then replace the target
def load_day(day, fail_at=None):
    target = Path(f"sales/day={day}/part.csv")
    target.parent.mkdir(parents=True, exist_ok=True)
    tmp = target.with_name(f".{target.name}.tmp")
    with tmp.open("w", encoding="utf-8") as f:
        for row in read_source(fail_at):
            f.write(f"{row}\n")
    tmp.replace(target)    # swap in only when complete

This step prints nothing; it prepares the data for the next step.

Let's fail it once, then run it twice in a row.

Python - Fail, rerun, rerun: always the same three rows
part = Path("sales/day=2026-10-23/part.csv")
try:
    load_day("2026-10-23", fail_at=2)
except ConnectionError as e:
    print("run 1 failed:", e)
print("partition exists:", part.exists())
load_day("2026-10-23")
load_day("2026-10-23")                  # rerun: same file
print(part.read_text(encoding="utf-8").splitlines())
Output
run 1 failed: source dropped at row 3
partition exists: False
['A,5', 'B,7', 'C,2']

After the failed run, partition exists: False. After two runs in a row, the file has exactly three rows: ['A,5', 'B,7', 'C,2'].

In a database, it's the same idea: replace the day's slice in one transaction, or upsert on the key, as in the next post.

Drive each run by the logical date

Pass the date in, and never use today's clock to pick the slice.

Question 6: Connection settings differ between dev and prod. How do you manage configuration in a Python pipeline?

Keep the code identical in every environment, and change only the configuration. The environment name comes from an environment variable, PIPELINE_ENV, set by the scheduler or the deployment.

Settings that aren't secret go in a small TOML file per environment:

config/dev.toml
db_host = "localhost"
batch_size = 500
config/prod.toml
db_host = "sql-prod.internal"
batch_size = 5000

tomllib reads them, in the standard library since Python 3.11. We load them once into a frozen dataclass: a typo in a key fails right away, and nothing changes in the middle of a run.

Python - Settings: one TOML file per environment, loaded into a frozen dataclass
import tomllib
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Settings:
    db_host: str
    batch_size: int

def load_settings(env: str) -> Settings:
    with open(f"config/{env}.toml", "rb") as f:
        return Settings(**tomllib.load(f))

This step prints nothing; it prepares the data for the next step.

Now let's load dev, then set the environment to prod, and finally read the database password.

Python - The environment picks the file; a missing secret fails fast
import os
print(load_settings("dev"))
os.environ["PIPELINE_ENV"] = "prod"  # set by the scheduler
env = os.environ.get("PIPELINE_ENV", "dev")
print(load_settings(env))
password = os.environ["DB_PASSWORD"]  # secret: fail fast
Output (expected error)
Settings(db_host='localhost', batch_size=500)
Settings(db_host='sql-prod.internal', batch_size=5000)
KeyError: 'DB_PASSWORD'

Dev gives localhost and a batch size of 500. With the environment set to prod, the same code gives sql-prod.internal and 5000. The password isn't set, so os.environ["DB_PASSWORD"] fails fast with KeyError: 'DB_PASSWORD'.

Secrets never go in those files or in Git: read them from the environment or a secret manager like Azure Key Vault.

Two tips

On bigger projects, pydantic-settings adds type checks for environment values. And log the environment name at startup, never the secrets.

Scenario 7: The 2 AM job failed and nobody knew why until noon. How do you make the pipeline observable?

First, what happened:

  • 2:00 AM: the job fails. The script caught the error, printed it to a console nobody reads, and exited with code 0.
  • The scheduler showed success, so no alert was sent.
  • 12:00 PM: the first alarm was an analyst with an empty report.

Fix one: fail loudly. A run wrapper logs the start and the finish. On any exception it calls log.exception, sends an alert and returns exit code 1, so the scheduler marks the run failed.

Python - A run wrapper: log start and end, log.exception, alert, exit code
def run_job(name, run_id, task):
    ctx = {"run_id": run_id}
    log.info("%s started", name, extra=ctx)
    try:
        rows = task()
    except Exception:
        log.exception("%s failed", name, extra=ctx)
        alert(f"{name} failed, run {run_id}")
        return 1
    log.info("%s loaded %s rows", name, rows, extra=ctx)
    return 0

This step prints nothing; it prepares the data for the next step.

Fix two: structured logs. A JSON formatter writes one object per line, with the level, the message and a run ID passed through extra. In production, also add the time and the full traceback.

Python - A JSON formatter: one JSON object per log line
import json

class JsonFormatter(logging.Formatter):
    def format(self, record):
        doc = {"level": record.levelname,
               "msg": record.getMessage(),
               "run_id": getattr(record, "run_id", None)}
        if record.exc_info:
            doc["error"] = repr(record.exc_info[1])
        return json.dumps(doc)

This step prints nothing; it prepares the data for the next step.

basicConfig attaches it at the entry point. force=True is only there because this demo already set up text logging in Question 4. The alert function is a fake that stands in for Teams or a pager.

Python - Entry point: attach the JSON handler; a fake alert
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
# force: this demo already set up text logging in Q4
logging.basicConfig(handlers=[handler], level=logging.INFO,
                    force=True)

def alert(text):  # fake: stands in for Teams or a pager
    print("ALERT:", text)

This step prints nothing; it prepares the data for the next step.

Now let's run it with tonight's failure, a source timeout.

Python - Tonight's failure: the source times out
def extract_orders():
    raise TimeoutError("source API timed out")    # tonight

code = run_job("nightly_orders", "r-1024", extract_orders)
print("exit code", code)  # real job: sys.exit(code)
Output
{"level": "INFO", "msg": "nightly_orders started", "run_id": "r-1024"}
{"level": "ERROR", "msg": "nightly_orders failed", "run_id": "r-1024", "error": "TimeoutError('source API timed out')"}
ALERT: nightly_orders failed, run r-1024
exit code 1

Two JSON lines for run r-1024, the error in its own field, TimeoutError('source API timed out'), the alert, and exit code 1. In the real job, pass that code to sys.exit. In Azure Monitor or Datadog, search every run by its ID.

Fix three: monitor the data. Log row counts, and add a freshness check: if the orders table isn't loaded by 6 AM, alert, even if the job never started.

Now

the on-call engineer knows at 2 AM, not at noon.

Key points to remember

  • Never except: pass: catch what you expect, keep the rejects
  • Custom exceptions stop the load; the exit code tells the scheduler
  • raise ... from keeps the original cause
  • logging configured once; logger.exception in except blocks
  • Idempotent reruns, config per environment, JSON logs and alerts

The full script

Here is everything in one script: the sample data and every step from this post, in order. Copy it and run it top to bottom.

Show the full Python script (sample data and every step)
Full script - copy and run top to bottom
# ========================================================================
# Python Interview Q&A #7 - Error handling, logging and reliable pipelines
# TechBrothersIT. Sample data is invented for teaching.
# Every step below was run with Python 3.14.6 and pandas 3.1.0; the outputs in the video and the blog
# post are the real outputs. Run it in an empty folder: it writes small sample files.
# ========================================================================

# Step 0: sample data
import os
from pathlib import Path

# Q6: start from a clean environment, and write one small config file per environment
os.environ.pop("PIPELINE_ENV", None)
os.environ.pop("DB_PASSWORD", None)
Path("config").mkdir()
Path("config/dev.toml").write_text('db_host = "localhost"\nbatch_size = 500\n', encoding="utf-8")
Path("config/prod.toml").write_text('db_host = "sql-prod.internal"\nbatch_size = 5000\n', encoding="utf-8")

# Q5: stands in for the real source system. It yields rows and can drop the connection at a given row.
SOURCE_ROWS = ["A,5", "B,7", "C,2"]


def read_source(fail_at=None):
    for i, row in enumerate(SOURCE_ROWS):
        if i == fail_at:
            raise ConnectionError(f"source dropped at row {i + 1}")
        yield row


# Step 1: The bad loader: try, bare except, pass
rows = [(1, "5"), (2, "n/a"), (3, "2")]   # (id, qty)

def load_bad(rows):
    loaded = []
    for row_id, qty in rows:
        try:
            loaded.append((row_id, int(qty)))
        except:
            pass
    return loaded

print(load_bad(rows))

# Step 2: Catch only the expected errors and keep the rejected rows
def load(rows):
    good, rejected = [], []
    for row_id, qty in rows:
        try:
            good.append((row_id, int(qty)))
        except ValueError as e:
            rejected.append((row_id, str(e)))
    return good, rejected

good, rejected = load(rows)
print(f"loaded {len(good)}, rejected {len(rejected)}")
print(*rejected, sep="\n")

# Step 3: A custom exception hierarchy and a business rule that raises
class PipelineError(Exception):
    """Base class for every error this pipeline raises."""

class DataQualityError(PipelineError):
    """A business rule failed: stop the load."""

def check_reject_rate(loaded, rejected, limit=5.0):
    pct = 100 * rejected / (loaded + rejected)
    if pct > limit:
        raise DataQualityError(
            f"reject rate {pct:.1f}% > {limit}%")

# Step 4: The rule fails for a batch with 60 rejects in 1,000
# This step is EXPECTED TO FAIL: it shows the error the video explains.
try:
    check_reject_rate(loaded=940, rejected=60)
except Exception as e:
    print(type(e).__name__ + ":", e)

# Step 5: The entry point catches the rule failure and returns an exit code
def run_job(loaded, rejected):
    try:
        check_reject_rate(loaded, rejected)
    except DataQualityError as e:
        print("load stopped:", e)
        return 1
    else:
        print("rule passed: publish the batch")
        return 0

print("exit code", run_job(990, 10))
print("exit code", run_job(940, 60))

# Step 6: Chain the low-level error with raise ... from
class SourceFileError(PipelineError):
    """A source file has a value we can't parse."""

def parse_qty(text, file, row):
    try:
        return int(text)
    except ValueError as e:
        msg = f"{file} row {row}: bad quantity {text!r}"
        raise SourceFileError(msg) from e

# Step 7: The new error keeps the original as its __cause__
try:
    parse_qty("12x", "orders.csv", 3)
except SourceFileError as e:
    for exc in (e, e.__cause__):
        print(f"{type(exc).__name__}: {exc}")

# Step 8: Configure logging once at the entry point
import logging
import sys

logging.basicConfig(
    level=logging.INFO, stream=sys.stdout,
    format="%(levelname)s %(name)s: %(message)s")
# in etl/orders.py this is logging.getLogger(__name__)
log = logging.getLogger("etl.orders")

log.debug("row detail, hidden at INFO")
log.info("loaded %s rows from %s", 940, "orders.csv")
log.warning("rejected %s rows", 60)

# Step 9: logger.exception logs the traceback, then raise fails the job
# This step is EXPECTED TO FAIL: it shows the error the video explains.
try:
    for row_no, text in enumerate(["5", "12x"], start=1):
        try:
            qty = int(text)
        except ValueError:
            log.exception("bad quantity, row %s", row_no)
            raise
except Exception as e:
    print(type(e).__name__ + ":", e)

# Step 10: The bug: append mode, and the first run fails at row 3
from pathlib import Path

def load_append(day, fail_at=None):
    with open("sales.csv", "a", encoding="utf-8") as f:
        for row in read_source(fail_at):
            f.write(f"{day},{row}\n")

try:
    load_append("2026-10-23", fail_at=2)
except ConnectionError as e:
    print("run 1 failed:", e)

# Step 11: The rerun appends everything again
load_append("2026-10-23")                    # the rerun
print(Path("sales.csv").read_text(encoding="utf-8"), end="")

# Step 12: Idempotent: write the day to a temp file, then replace the target
def load_day(day, fail_at=None):
    target = Path(f"sales/day={day}/part.csv")
    target.parent.mkdir(parents=True, exist_ok=True)
    tmp = target.with_name(f".{target.name}.tmp")
    with tmp.open("w", encoding="utf-8") as f:
        for row in read_source(fail_at):
            f.write(f"{row}\n")
    tmp.replace(target)    # swap in only when complete

# Step 13: Fail, rerun, rerun: always the same three rows
part = Path("sales/day=2026-10-23/part.csv")
try:
    load_day("2026-10-23", fail_at=2)
except ConnectionError as e:
    print("run 1 failed:", e)
print("partition exists:", part.exists())
load_day("2026-10-23")
load_day("2026-10-23")                  # rerun: same file
print(part.read_text(encoding="utf-8").splitlines())

# Step 14: Settings: one TOML file per environment, loaded into a frozen dataclass
import tomllib
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Settings:
    db_host: str
    batch_size: int

def load_settings(env: str) -> Settings:
    with open(f"config/{env}.toml", "rb") as f:
        return Settings(**tomllib.load(f))

# Step 15: The environment picks the file; a missing secret fails fast
# This step is EXPECTED TO FAIL: it shows the error the video explains.
try:
    import os
    print(load_settings("dev"))
    os.environ["PIPELINE_ENV"] = "prod"  # set by the scheduler
    env = os.environ.get("PIPELINE_ENV", "dev")
    print(load_settings(env))
    password = os.environ["DB_PASSWORD"]  # secret: fail fast
except Exception as e:
    print(type(e).__name__ + ":", e)

# Step 16: A JSON formatter: one JSON object per log line
import json

class JsonFormatter(logging.Formatter):
    def format(self, record):
        doc = {"level": record.levelname,
               "msg": record.getMessage(),
               "run_id": getattr(record, "run_id", None)}
        if record.exc_info:
            doc["error"] = repr(record.exc_info[1])
        return json.dumps(doc)

# Step 17: Entry point: attach the JSON handler; a fake alert
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
# force: this demo already set up text logging in Q4
logging.basicConfig(handlers=[handler], level=logging.INFO,
                    force=True)

def alert(text):  # fake: stands in for Teams or a pager
    print("ALERT:", text)

# Step 18: A run wrapper: log start and end, log.exception, alert, exit code
def run_job(name, run_id, task):
    ctx = {"run_id": run_id}
    log.info("%s started", name, extra=ctx)
    try:
        rows = task()
    except Exception:
        log.exception("%s failed", name, extra=ctx)
        alert(f"{name} failed, run {run_id}")
        return 1
    log.info("%s loaded %s rows", name, rows, extra=ctx)
    return 0

# Step 19: Tonight's failure: the source times out
def extract_orders():
    raise TimeoutError("source API timed out")    # tonight

code = run_job("nightly_orders", "r-1024", extract_orders)
print("exit code", code)  # real job: sys.exit(code)
Next in this series

Part 8: Python and Databases

The sample data on this page is invented for teaching. Every output is the real output of the code above it, run with Python 3.14.6 and pandas 3.1.0. Part of the Real Time Python for Data Engineers Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Python and library documentation for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.