Callbacks: tracking every call
A callback is a class that LiteLLM calls after every request, passing it the request, the response, the timing and the cost, so logging and spend tracking live outside the calling code.
Last updated: 12 Oct, 2026 · LiteLLM 1.105
Exceptions: one set for every provider handled a failure where the call was made. A callback handles both outcomes in one place for every call, which is how a team finds out who spent what and which calls failed.
Syntax: subclass CustomLogger, define the events you want and register an instance in litellm.callbacks.
from litellm.integrations.custom_logger import CustomLogger
class Tracker(CustomLogger):
def log_success_event(self, kwargs, response_obj, start_time, end_time):
... # runs after a call that worked
def log_failure_event(self, kwargs, response_obj, start_time, end_time):
... # runs after a call that raised
litellm.callbacks = [Tracker()]Writing the smallest CustomLogger
A callback class needs only the event methods you want. LiteLLM calls log_success_event after each successful call, with four arguments. kwargs holds the request, including the model and the cost. response_obj is the response. The last two are the start and end times. litellm.callbacks takes a list of instances.
class Report(CustomLogger):
def log_success_event(self, kwargs, response_obj, start_time, end_time):
model = kwargs["model"] # the model that answered
tokens = response_obj.usage.total_tokens
print("finished:", model, tokens, "tokens")
litellm.callbacks = [Report()] # register it once, near the topTracking cost per team with a CustomLogger
A class can hold state. This one keeps a running cost for each team, and a list of failures. metadata is an argument you add to a call. It travels to the callback without being sent to the model, and it is where the team name goes.
import time
import litellm
from litellm.integrations.custom_logger import CustomLogger
class Tracker(CustomLogger):
def __init__(self):
super().__init__()
self.cost_by_team = {}
self.failures = []
def log_success_event(self, kwargs, response_obj, start_time, end_time):
team = kwargs["litellm_params"]["metadata"]["team"]
self.cost_by_team[team] = self.cost_by_team.get(team, 0) + kwargs["response_cost"]
def log_failure_event(self, kwargs, response_obj, start_time, end_time):
self.failures.append((kwargs["model"], type(kwargs["exception"]).__name__))
tracker = Tracker()
litellm.callbacks = [tracker]
ask = [{"role": "user", "content": "hi"}]
for team in ["billing", "shipping", "billing"]:
litellm.completion(model="groq/openai/gpt-oss-20b", messages=ask, max_tokens=400, metadata={"team": team})
try:
litellm.completion(model="groq/openai/not-a-model", messages=ask, max_tokens=400)
except litellm.NotFoundError:
pass
time.sleep(1)
for team, cost in tracker.cost_by_team.items():
print(team, f"{cost:.8f}")
print(tracker.failures)billing 0.00003630
shipping 0.00001380
[('openai/not-a-model', 'NotFoundError')]LiteLLM runs callbacks in a background thread so they never slow a reply, which means a callback can finish after completion() has returned. The sleep before the totals gives the last one time to finish, and a real service reads its totals later, from a log or a database.
Reading what the tracker collected
- Billing appears once with two calls added together, and shipping once with one. The tracker summed
response_costby team, the field the previous lessons read from a response. - The failed call was recorded.
log_failure_eventran for the unknown model, andkwargs["exception"]held the exception, the sameNotFoundErrorthe caller caught. - The caller's code never changed. It made calls and caught the one error, and the tracker watched from outside.
Callbacks for sync calls, async calls and streams
| Event | Sync method | Async method |
|---|---|---|
| A call succeeded | log_success_event | async_log_success_event |
| A call failed | log_failure_event | async_log_failure_event |
| Before a call is sent | log_pre_api_call | Not covered here |
A class can define any of these. Use the async pair when the program calls acompletion. LiteLLM's documentation also lists ready-made callbacks for observability tools, configured by name, which Observability: watching every call uses.
Where you use callbacks
- Spend per team, key or customer, kept in a dictionary or written to a database.
- An alert when a model's failure count passes a limit.
- A call log with the model, tokens, cost and latency, computed from
start_timeandend_time.
Related
- Previous: Exceptions: one set for every provider
- Next: Endpoints beyond chat
- Reference: Custom callbacks in the LiteLLM docs
- Print
(end_time - start_time).total_seconds()beside each team's cost, to see how long each call took. - Print
kwargs["model"]inlog_failure_eventas well as the exception class. - Remove the
time.sleep(1)from the tracker example and see whether the totals come out short.
Little by little, you're building something great.