Observability Per Tenant in Laravel: Logs, Metrics and Errors by Company: 07 of 08
How to answer which company is affected: a company id in every log line from web, queue and console, what to measure per tenant and what not to, how to tag errors, and the privacy and cost traps.
Imagine a customer writes to support: the app has been slow since Tuesday. You open the logs. There are two million lines from that week, and not one of them says which company it belongs to. You can see that something is slow. You can't see for whom, or whether the customer who wrote is the only one.
In a single-tenant app that gap is annoying. In a multi-tenant one it hides the most useful question you have: which company is this about? This article is about adding that answer to logs, metrics and error reports, without drowning in data or leaking someone's personal information into your log store.
The Three Questions
Observability for a shared system boils down to three questions, and each needs the company attached:
- What did company X see yesterday? Support asks this. It needs logs you can filter by company.
- Which company is hurting the others? This is the noisy-neighbor question. It needs timing and volume grouped by company.
- Who is affected by this error? Without that, a stack trace is one stack trace, whether it hit one customer or all of them.
The rest of the article is about getting a company_id into each of the three, in the cheapest way that works.
One Key in Every Log Line
Laravel's Context does most of this work. Per the Context docs, anything you add is appended as metadata to the log entries written during the request, and it is also captured when a job is dispatched and restored while that job runs. One line where the company is resolved, and every later log entry carries it.
The tenant article already has one place that every entry point goes through: TenantContext::runAs. The web middleware uses it, and so do the scheduled fan-out and console commands. That makes it the right home for the context key too. Context::scope runs a callback with extra data and puts the context back afterwards:
public function runAs(int $companyId, Closure $callback): mixed
{
$previous = $this->companyId;
$this->companyId = $companyId;
$result = null;
try {
Context::scope(function () use ($callback, &$result): void {
$result = $callback();
}, data: ['company_id' => $companyId]);
return $result;
} finally {
$this->companyId = $previous;
}
}
Now a log line written from a controller, a queued listener or a nightly command has the company on it, with no extra code at the call site. Where the field ends up in your log output depends on the log formatter, so check one real line before building dashboards on it.
Context also has hidden data. Hidden values are not appended to logs, which makes them a place for things you need in code but must not print.
Log the Request Once, With Its Cost
A company id on every line is useful, and a single line per request that says how long it took and how it ended is more useful. It gives you the raw material for the noisy-neighbor question:
final class LogRequestCompleted
{
public function handle(Request $request, Closure $next): Response
{
$started = hrtime(true);
$response = $next($request);
Log::info('request.completed', [
'route' => $request->route()?->getName(),
'status' => $response->getStatusCode(),
'duration_ms' => (int) ((hrtime(true) - $started) / 1_000_000),
]);
return $response;
}
}
Order matters. This middleware has to sit after the tenant middleware in the route group, because the tenant middleware wraps everything after it in runAs. Put it before, and the line is written outside the scope and loses its company.
Metrics: Count What You Would Support or Bill
The temptation is to add company_id as a label to every metric. In Prometheus-style systems each distinct label value creates a separate time series. A few hundred companies is fine. Tens of thousands multiplies every metric by that number, and the monitoring bill follows.
A split that has worked in practice:
- Infrastructure metrics (request rate, queue depth, error rate) stay aggregated, without a company label.
- Per-company questions are answered from logs, which are built for high-cardinality filtering, or from usage data in your own database.
That second option fits the earlier articles well. A listener on InvoiceApproved can increment a per-company, per-day counter in a small usage table. That table feeds the plan limits, the billing conversation and the support dashboard from one source. Note that it is a deliberate cross-company write, so it belongs on the scope-bypass allowlist from the testing article.
Errors: Tag the Company
Your error tracker needs the company the same way your logs do. Most trackers let you attach a tag or extra data to the current scope. Set it where the tenant is resolved, next to the context line. The Context docs page doesn't say whether context is attached to exception reports, so don't rely on it. Check what your tracker records on a test exception, and add the tag explicitly if it doesn't.
With the tag, "is this one customer or everyone?" becomes a filter. A new error that shows up for a single company points at that company's data. The same error across many companies points at the code.
What to Keep Out and What It Costs
Log the id, not the person. A company id in a log line is a pointer. A company name, a contact email or an invoice total is data you now have to protect, retain and delete on request. Keep names and emails out of log messages and look them up from the id when you need them.
Three costs to plan for:
- Volume. One extra line per request adds up. Sample or drop it for health checks and static assets, and set a retention period you can defend.
- Payload size. Context is captured alongside the job payload at dispatch, so keep it to small identifiers. Don't put objects or arrays in it.
- Cardinality, as above: per-company labels on every metric are the expensive mistake.
Back to Tuesday
In the scenario from the opening, with the id on every line the investigation goes differently. Filter request.completed for the week, group by company, and compare the slowest percentiles. Suppose one company's export endpoint is far above the rest from Tuesday on. Now the ticket is no longer "the app is slow". It is "one company's export is slow, and it's starting to take workers from the others". That is a problem you can act on: look at that company's data size, move the export to a queue, or limit how often it can run.
That result is hypothetical. The method isn't: filter by company, group, compare, then decide.
Conclusion
The support ticket in the opening was unanswerable because the logs had no idea who they were about. One key added in one place, runAs, fixes that for the web, the queue and the console. A single request line, aggregate metrics, per-company usage in your own database, and a company tag on errors cover the three questions. The cost is a little log volume and some discipline about what goes in.
That closes the main line of the series. The isolation work keeps companies apart, and this gives you a way to see each one separately. One optional article remains: adding a second wall at the database with PostgreSQL row-level security.