Start free trial
Start free trial Log in

14-day free trial. No credit card.

How to Track Users in Laravel Monitoring

Attach user identity to every request, exception and job, then look up what any one user ran into.

  • Guide
  • 3 min read

How do I attach user identity to Laravel monitoring?

With the Nightwatch package (which NightOwl reads), the authenticated user is recorded automatically. Call Nightwatch::user() in AppServiceProvider::boot() to choose the name and username stored with the ID, and add user fields to your log lines with a middleware (avoid sensitive PII). Requests, exceptions and queued jobs then carry the user ID, and support tickets referencing a specific customer can be investigated without grep-ing logs.

Updated

The first time this matters is usually a support ticket. A customer says checkout failed at 2pm, and you need to find what actually happened to them, not to everyone. If your telemetry doesn't know who hit each request, the answer is grep and guesswork. Attaching user identity to every event turns that question into a filter.

Middleware approach

The Nightwatch package, which NightOwl reads, records the authenticated user on its own: the ID, plus a name and username that default to the user's name and email. Those three fields are all it stores. To choose what fills name and username, register a resolver once in AppServiceProvider::boot():

app/Providers/AppServiceProvider.phpphp
use Laravel\Nightwatch\Facades\Nightwatch;

public function boot(): void
{
    Nightwatch::user(fn ($user) => [
        'name' => $user->name,
        'username' => $user->email,
    ]);
}

Anything else you want next to the user, like a plan or team ID, belongs in your log context. A middleware runs on every authenticated request and can push those fields onto every log line:

app/Http/Middleware/AttachUserTelemetry.phpphp
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AttachUserTelemetry
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();

            // Push into Laravel's log context (appears on every log line)
            Log::withContext([
                'user_id' => $user->id,
                'user_email' => $user->email,
                'user_plan' => $user->subscription_plan ?? null,
            ]);
        }

        return $next($request);
    }
}

Register it on routes that should be tracked:

bootstrap/app.phpphp
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \App\Http\Middleware\AttachUserTelemetry::class,
    ]);
    $middleware->api(append: [
        \App\Http\Middleware\AttachUserTelemetry::class,
    ]);
})

What to attach (and what not to)

Attach

  • User ID (stable, non-secret)
  • Email (useful for support)
  • Plan or subscription tier
  • Team / org ID for B2B apps
  • Feature flag variant

Avoid

  • Passwords, password hashes
  • Payment card info, bank details
  • Government IDs, SSNs
  • Full addresses, phone numbers
  • Any field users haven't consented to share

Frontend → backend correlation

For full visibility, your front end should generate a request ID and pass it via header on every API call. The backend picks it up, adds it to every log line and echoes it back in the response.

Frontend (every fetch)

js
const requestId = crypto.randomUUID();
fetch('/api/orders', {
    headers: {
        'X-Request-Id': requestId,
        // ...
    },
});
app/Http/Middleware/EnsureRequestId.phpphp
public function handle($request, Closure $next)
{
    $id = $request->header('X-Request-Id') ?? (string) \Illuminate\Support\Str::uuid();
    $request->attributes->set('request_id', $id);

    Log::withContext(['request_id' => $id]);

    $response = $next($request);
    $response->headers->set('X-Request-Id', $id);

    return $response;
}

Two places it quietly breaks

Middleware order. Nightwatch resolves the user itself at the end of the request, so its user field doesn't depend on where your middleware sits. Your log-context middleware does, on routes behind a token guard such as Sanctum: the default guard only switches once the auth middleware has run, so a middleware placed earlier sees Auth::check() return false and attaches nothing. Session-based web routes resolve the user from the session either way. If user fields are missing from logs on API routes but not web routes, check the middleware order on those routes first.

Queued jobs. Nightwatch carries the ID of the user who dispatched a job into that job's records, which is how NightOwl can list a user's queued jobs. Log::withContext doesn't cross that boundary: the job runs later, in another process, with no authenticated user. For log lines inside the job, add the fields with Laravel's Context facade (Context::add()), which is passed into queued jobs, or pass the ID into the job's constructor. Artisan commands and scheduled tasks record no user at all.

Look up any user and see what they hit

The Nightwatch package records the signed-in user's ID, name and username on its own. NightOwl's Users page lists each user with their request, queued job and exception counts. Open a user to see their requests chart, top routes, slowest routes at P95 and top queued jobs.

No credit card needed.

Terminal
composer require nightowl/agent
php artisan nightowl:install
php artisan nightowl:agent

Frequently asked questions

Anything else, write to support@usenightowl.com

How do I track users in my Laravel monitoring?

Make sure the authenticated user is attached to your telemetry, so requests, exceptions and jobs carry the user's ID. This lets you answer 'which users hit this bug?' or 'is this slow endpoint slow for everyone or just one customer?' Most APMs (NightOwl, Nightwatch Cloud, Sentry) support this out of the box. With the Nightwatch package the authenticated user is recorded automatically, and Nightwatch::user() in a service provider decides which name and username go with the ID.

Is tracking users in monitoring a privacy risk?

It can be. Attach the user ID and only the fields support actually needs, such as email and plan, and remember that an email address is personal data under GDPR. Don't send payment data, government IDs, or free-form text you haven't reviewed. Check your privacy policy and local regulations (GDPR). You may need to disclose that you process user IDs in a monitoring system. BYOD tools like NightOwl keep the data in your database, which simplifies compliance.

How do I find all the exceptions a specific user hit?

Your monitoring tool needs to index exceptions by user_id. In NightOwl, pick the user in the dashboard's user filter and the Exceptions page shows only the exception groups that user hit. The Users page lists each user with their request, queued job and exception counts. Without that, you're grep-ing log files or manually querying exception tables.

Should I track user sessions or just user IDs?

User ID is enough for backend monitoring: you want to know 'which user hit this error,' not reconstruct their click path. Session tracking is a front-end concern (RUM, session replay) handled by separate tools like FullStory or LogRocket. For Laravel backend monitoring, user ID + email is the standard.

How do I correlate a user's frontend actions with backend events?

Generate a request/trace ID in the front end and pass it through every API call in an X-Request-Id header. Log that ID on the backend. Now a support ticket that includes the front-end trace ID can be searched in your backend logs to find the exact request. Laravel middleware can auto-generate one if the header is missing.

Does Laravel ship with user tracking for monitoring?

Laravel's Request::user() gives you the authenticated user, but there's no built-in telemetry pipeline. You need either a manual setup (attach user to logs + APM SDK calls) or a tool that ships with Laravel-native user tracking. The Nightwatch package records the user ID automatically on requests, exceptions and queued jobs, which NightOwl surfaces on its Users page. Commands and scheduled tasks don't record a user.

How do I handle user tracking for guest traffic?

Use a persistent first-party cookie so guest activity has a stable ID, even if they're not authenticated. Write that ID to your log context. When the guest converts to a user, you can link the pre-auth activity to the user account retroactively.

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial

Related

Look up a user on your own app

Nightwatch already records who is signed in, so the Users page fills in as they make requests. No credit card needed.