Sub topic 10
Finding who uses the API with Event Monitoring
This chapter assumes you can call the Salesforce REST API with an access token and write basic SOQL. You should also have seen the REST Limits resource and the Sforce-Limit-Info header from earlier chapters. Those tools tell you how much of the daily API limit is used. They don't tell you who used it. Event Monitoring answers that question.
The problem: a total with no owner
Suppose DailyApiRequests shows 12,000 of 15,000 used by noon. You need to know which user, connected app, or client made those calls before you can fix anything. Candidates include a nightly sync, a reporting tool that polls, or a script someone left in a loop.
Event Monitoring records API activity as event log files. Each file is a CSV with one row per event. The ApiTotalUsage event type records API calls, so it can attribute usage to users and clients.
What you need first
Event log files are not available in every org. Keep these points in mind:
- Access comes with an Event Monitoring license, which is sold as an add-on (included in some Shield bundles). Without it, the
EventLogFileobject may be missing or return no useful data. - The integration user needs the View Event Log Files permission. Without it, queries return nothing or an authorization error.
- Files are generated after the fact. Daily files for a given day usually appear the next day, so this is for investigation. It is not live monitoring.
- Files are kept for a limited time, commonly 30 days. If you need a longer history, download and store the files yourself.
Check your edition's current documentation for exact retention and licensing, because these terms change.
Listing available log files
EventLogFile is a normal sObject, so you query it with SOQL. This query lists the last seven days of API usage logs:
SELECT Id, EventType, LogDate, LogFileLength
FROM EventLogFile
WHERE EventType = 'ApiTotalUsage'
AND LogDate = LAST_N_DAYS:7
ORDER BY LogDate DESCEach row describes one file. The useful fields are:
| Field | Meaning |
|---|---|
| `Id` | Identifier used to download the file |
| `EventType` | Kind of events in the file, here `ApiTotalUsage` |
| `LogDate` | The day the events cover |
| `LogFileLength` | Size of the file in bytes |
| `Interval` | Whether the file is `Daily` or `Hourly` (hourly files exist only for some setups) |
| `LogFileFieldNames` | Comma-separated column names in the CSV |
Two edge cases come up often. First, a day with no matching row doesn't mean no API calls happened. The file may not be generated yet, or your user may lack access. Second, LogFile is a blob field, so you can't SELECT its contents in a normal query. You fetch it from a separate URL.
Run the query through the REST query endpoint, or use any SOQL tool you prefer. Use LogFileFieldNames to see the exact columns before you write parsing code, because the set of columns can grow over time.
Downloading and reading a log file
The file content is served from the LogFile field of the record:
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/sobjects/EventLogFile/$LOG_FILE_ID/LogFile" \
-o api_total_usage.csv
head -n 3 api_total_usage.csvThe first line is the header row. Typical ApiTotalUsage columns include the user ID, the connected app name, the client name, the API family and resource called, and the HTTP method. Column names are uppercase with underscores, for example USER_ID, CONNECTED_APP_NAME, and CLIENT_NAME. The exact list depends on your API version and org, so read your own header row.
Files can be large on busy orgs. For big files, stream the response to disk instead of holding it in memory.
Aggregating usage by user and client
A raw log has one row per call. The useful view is a count per user and client. This script finds the newest ApiTotalUsage file, downloads it, and ranks the top callers:
import csv
import io
import os
from collections import Counter
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
headers = {"Authorization": f"Bearer {token}"}
base = f"{instance_url}/services/data/v60.0"
soql = (
"SELECT Id, LogDate FROM EventLogFile "
"WHERE EventType = 'ApiTotalUsage' "
"ORDER BY LogDate DESC LIMIT 1"
)
resp = requests.get(
f"{base}/query", headers=headers, params={"q": soql}, timeout=30
)
resp.raise_for_status()
records = resp.json()["records"]
if not records:
raise SystemExit("No ApiTotalUsage log files found (check license and permissions).")
file_id = records[0]["Id"]
log_date = records[0]["LogDate"]
log = requests.get(
f"{base}/sobjects/EventLogFile/{file_id}/LogFile",
headers=headers,
timeout=120,
)
log.raise_for_status()
reader = csv.DictReader(io.StringIO(log.text))
print("Columns:", reader.fieldnames)
counts = Counter()
for row in reader:
key = (
row.get("USER_ID", ""),
row.get("CONNECTED_APP_NAME", "") or "(none)",
row.get("CLIENT_NAME", "") or "(none)",
)
counts[key] += 1
print(f"Top API callers for {log_date}:")
for (user_id, app, client), n in counts.most_common(10):
print(f"{n:>8} user={user_id} app={app} client={client}")Two details matter here. The script calls .get() so a missing column produces an empty string instead of a crash, which is useful if the column set differs between orgs. It also prints reader.fieldnames so you can see what your file contains.
Because rows hold user IDs and not names, resolve the top IDs with one more query:
SELECT Id, Username, Name, Profile.Name
FROM User
WHERE Id IN ('005xx0000012345AAA', '005xx0000067890AAA')Replace the IDs with the ones from your output.
Reading the results
Look for patterns, not only the largest count.
- One user with a very high count and no connected app. This is often a script or tool using a username and password or a session token directly. Ask the owner what it does.
- One connected app dominating. Check how often it polls and whether it could use bulk operations or event-driven delivery instead.
- Many users from the same client. A shared tool, such as a data loader or BI connector, may be running per person when one scheduled job would do.
- Integration users with high counts at odd hours. A retry loop that never backs off can burn thousands of calls. This ties into the retry handling covered later in this tutorial.
- A sudden jump on one day. Compare counts day by day. A new deployment or a changed schedule usually explains it.
Not every logged row necessarily counts against the daily limit. The log includes a column for whether a call counts against the limit, and its name may vary by version. Check your header row and filter on it if it exists. Otherwise your totals may exceed the number shown in DailyApiRequests.
Gotchas and failure modes
| Symptom | Likely cause | What to do |
|---|---|---|
| Query returns zero rows | Missing license or permission, or file not yet generated | Confirm access with an admin, then retry the next day |
| `INVALID_TYPE` for `EventLogFile` | Object not available in this org | Confirm Event Monitoring is enabled |
| Totals don't match the Limits resource | Time zones, rolling 24-hour window versus calendar-day log, or uncounted calls | Compare over several days and filter on the limit-counting column |
| Script runs out of memory | File is large | Stream the download and process line by line |
| Column missing in parsing | Column set differs by version | Print `fieldnames` and use `.get()` |
The window mismatch deserves attention. The daily API limit uses a rolling 24-hour period, while a log file covers one LogDate day in UTC. Don't expect the two totals to match exactly. Use the logs to rank callers, not to reproduce the limit to the last request.
How this fits with the other tools
Each tool you've met answers a different question:
- The Limits resource says how much is left now.
Sforce-Limit-Infosays the same thing on every call, with no extra request.- Setup pages give a quick overview and notifications.
- Event Monitoring says who made the calls, after the fact.
A common workflow starts with an alert from the first tools. It then uses ApiTotalUsage logs to find the heavy caller, and finishes with a fix such as batching or caching.
Exercise
Your daily API usage hit 90% yesterday. The Limits resource shows only totals. Which Event Monitoring object and event type would you query to find the heaviest caller, and why can't you use it to see usage in real time?
Show answer
Query the EventLogFile object with EventType = 'ApiTotalUsage', then download the LogFile CSV and count rows by columns such as USERID, CONNECTEDAPPNAME, and CLIENTNAME. Log files are generated after the day ends, usually available the next day, so they support investigation and not live monitoring.
Exercise
A teammate's script prints the contents of the LogFile field by running SELECT LogFile FROM EventLogFile. It fails or returns no usable content. What is the correct way to get the CSV?
Show answer
LogFile is a blob field served from its own URL. Query EventLogFile for the Id, then send a GET request to /services/data/v60.0/sobjects/EventLogFile/<Id>/LogFile with the Authorization header and save the response as a CSV.