configure-nightwatch

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nightwatch Configuration Guide

Nightwatch 配置指南

This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
本技能可帮助配置Laravel Nightwatch的数据采集,以平衡可观测性、性能与隐私保护。涵盖所有事件类型的采样策略、过滤规则及脱敏方法。

Documentation Reference

文档参考

The Nightwatch Documentation is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
  • Filtering and Configuration - Core concepts for sampling, filtering, and redaction
  • Individual event type pages with specific configuration options:
    • Requests - Request sampling, header handling, payload capture
    • Commands - Command sampling and redaction
    • Queries - Query filtering and redaction
    • Cache - Cache event filtering by key or pattern
    • Jobs - Job filtering and sampling decoupling
    • Mail - Mail event filtering
    • Notifications - Notification filtering by channel
    • Exceptions - Exception sampling and throttling
    • Outgoing Requests - HTTP request filtering
  • reference.md - Quick lookup table by event type, production presets, and verification checklist
Nightwatch 官方文档是所有Nightwatch配置选项的权威且实时更新的信息来源。本技能提供实用指导和通用模式,但针对具体细节、环境变量及API行为,始终以官方文档作为主要参考依据。该文档包含以下全面内容:
  • 过滤与配置 - 采样、过滤与脱敏的核心概念
  • 各事件类型页面的特定配置选项:
    • 请求 - 请求采样、头部处理、负载捕获
    • 命令 - 命令采样与脱敏
    • 查询 - 查询过滤与脱敏
    • 缓存 - 按键或模式过滤缓存事件
    • 任务 - 任务过滤与采样解耦
    • 邮件 - 邮件事件过滤
    • 通知 - 按渠道过滤通知
    • 异常 - 异常采样与限流
    • 外部请求 - HTTP请求过滤
  • reference.md - 按事件类型、生产预设及验证清单分类的快速查询表

Data Collection Flow

数据采集流程

Nightwatch processes events through three stages:
  1. Sampling - Controls which entry points are captured (requests, commands, scheduled tasks)
  2. Filtering - Excludes specific events after sampling (queries, cache, mail, etc.)
  3. Redaction - Modifies captured data to remove/obfuscate sensitive information
Request/Command/Scheduled Task
       |
       v
   [Sampling?] ----NO----> Drop entire trace
       | YES
       v
   Events generated
       |
       v
   [Filtering?] ----YES---> Drop specific event
       | NO
       v
   [Redaction] ----------> Store modified data

Nightwatch通过三个阶段处理事件:
  1. 采样 - 控制哪些入口点会被捕获(请求、命令、定时任务)
  2. 过滤 - 在采样后排除特定事件(查询、缓存、邮件等)
  3. 脱敏 - 修改捕获的数据以移除/模糊敏感信息
Request/Command/Scheduled Task
       |
       v
   [Sampling?] ----NO----> Drop entire trace
       | YES
       v
   Events generated
       |
       v
   [Filtering?] ----YES---> Drop specific event
       | NO
       v
   [Redaction] ----------> Store modified data

Sampling Configuration

采样配置

Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
采样决定哪些入口点(请求、命令、定时任务)会触发完整链路采集。当入口点被采样时,所有相关事件都会被捕获。

Global Sample Rates

全局采样率

Configure via environment variables:
bash
undefined
通过环境变量配置:
bash
undefined

Default: 100% sampling (all requests/commands captured)

默认:100%采样(捕获所有请求/命令)

NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions

**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # 推荐:10%的请求 NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # 捕获所有命令 NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # 始终捕获异常

**建议**:生产环境中请求采样率从`0.1`(10%)开始,根据数据量和需求调整。

Route-Based Sampling

基于路由的采样

Apply different rates to specific routes using the
Sample
middleware:
php
use Illuminate\Support\Facades\Route;
use Laravel\Nightwatch\Http\Middleware\Sample;

// Sample admin routes at 100%
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
    // All admin routes sampled fully
});

// Sample API routes at 5%
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
    // API routes sampled sparingly
});

// Always sample critical endpoints
Route::post('/checkout', [CheckoutController::class, 'process'])
    ->middleware(Sample::always());

// Never sample health checks
Route::get('/health', [HealthController::class, 'check'])
    ->middleware(Sample::never());
使用
Sample
中间件为特定路由设置不同采样率:
php
use Illuminate\Support\Facades\Route;
use Laravel\Nightwatch\Http\Middleware\Sample;

// 管理员路由100%采样
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
    // 所有管理员路由全量采样
});

// API路由5%采样
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
    // API路由少量采样
});

// 关键端点始终采样
Route::post('/checkout', [CheckoutController::class, 'process'])
    ->middleware(Sample::always());

// 健康检查从不采样
Route::get('/health', [HealthController::class, 'check'])
    ->middleware(Sample::never());

Unmatched Route Sampling

未匹配路由采样

Handle 404/bot traffic with reduced sampling:
php
Route::fallback(fn () => abort(404))
    ->middleware(Sample::rate(0.01));  // 1% sampling for unmatched routes
为404/爬虫流量设置低采样率:
php
Route::fallback(fn () => abort(404))
    ->middleware(Sample::rate(0.01));  // 未匹配路由1%采样

Dynamic Sampling

动态采样

Sample based on runtime conditions (user role, request attributes):
php
use Closure;
use Illuminate\Http\Request;
use Laravel\Nightwatch\Facades\Nightwatch;

class SampleAdminRequests
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->user()?->isAdmin()) {
            Nightwatch::sample();  // Always sample admin requests
        }
        return $next($request);
    }
}
基于运行时条件(用户角色、请求属性)进行采样:
php
use Closure;
use Illuminate\Http\Request;
use Laravel\Nightwatch\Facades\Nightwatch;

class SampleAdminRequests
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->user()?->isAdmin()) {
            Nightwatch::sample();  // 管理员请求始终采样
        }
        return $next($request);
    }
}

Command Sampling

命令采样

Exclude specific commands from sampling:
php
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Laravel\Nightwatch\Facades\Nightwatch;

public function boot(): void
{
    Event::listen(function (CommandStarting $event) {
        if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
            Nightwatch::dontSample();
        }
    });
}
排除特定命令不进行采样:
php
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Laravel\Nightwatch\Facades\Nightwatch;

public function boot(): void
{
    Event::listen(function (CommandStarting $event) {
        if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
            Nightwatch::dontSample();
        }
    });
}

Vendor Commands

第三方命令

Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
php
Nightwatch::captureDefaultVendorCommands();

Nightwatch会自动忽略框架/内部命令。如需捕获可选择开启:
php
Nightwatch::captureDefaultVendorCommands();

Filtering Configuration

过滤配置

Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
过滤用于在采样后排除特定事件,以减少无效数据和配额消耗。

Database Queries

数据库查询

Filter all queries (disable query collection):
bash
NIGHTWATCH_IGNORE_QUERIES=true
Filter specific queries by SQL pattern:
php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Query;

public function boot(): void
{
    // Filter job table queries (PostgreSQL)
    Nightwatch::rejectQueries(function (Query $query) {
        return str_contains($query->sql, 'into "jobs"');
    });

    // Filter cache table queries (MySQL)
    Nightwatch::rejectQueries(function (Query $query) {
        return str_contains($query->sql, 'from `cache`')
            || str_contains($query->sql, 'into `cache`');
    });
}
过滤所有查询(禁用查询采集):
bash
NIGHTWATCH_IGNORE_QUERIES=true
按SQL模式过滤特定查询
php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Query;

public function boot(): void
{
    // 过滤任务表查询(PostgreSQL)
    Nightwatch::rejectQueries(function (Query $query) {
        return str_contains($query->sql, 'into "jobs"');
    });

    // 过滤缓存表查询(MySQL)
    Nightwatch::rejectQueries(function (Query $query) {
        return str_contains($query->sql, 'from `cache`')
            || str_contains($query->sql, 'into `cache`');
    });
}

Cache Events

缓存事件

Filter all cache events:
bash
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
Filter by cache key patterns:
php
Nightwatch::rejectCacheKeys([
    'my-app:users',                    // Exact match
    '/^my-app:posts:/',                // Regex: starts with my-app:posts:
    '/^[a-zA-Z0-9]{40}$/',             // Regex: session IDs
]);
Filter with callback:
php
use Laravel\Nightwatch\Records\CacheEvent;

Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
    return str_starts_with($cacheEvent->key, 'temp:');
});
过滤所有缓存事件
bash
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
按缓存键模式过滤
php
Nightwatch::rejectCacheKeys([
    'my-app:users',                    // 精确匹配
    '/^my-app:posts:/',                // 正则:以my-app:posts:开头
    '/^[a-zA-Z0-9]{40}$/',             // 正则:会话ID
]);
通过回调函数过滤
php
use Laravel\Nightwatch\Records\CacheEvent;

Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
    return str_starts_with($cacheEvent->key, 'temp:');
});

Mail Events

邮件事件

Filter all mail:
bash
NIGHTWATCH_IGNORE_MAIL=true
Filter specific mail:
php
use Laravel\Nightwatch\Records\Mail;

Nightwatch::rejectMail(function (Mail $mail) {
    return str_contains($mail->subject, 'Newsletter');
});
过滤所有邮件
bash
NIGHTWATCH_IGNORE_MAIL=true
过滤特定邮件
php
use Laravel\Nightwatch\Records\Mail;

Nightwatch::rejectMail(function (Mail $mail) {
    return str_contains($mail->subject, 'Newsletter');
});

Notification Events

通知事件

Filter all notifications:
bash
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
Filter by channel:
php
use Laravel\Nightwatch\Records\Notification;

Nightwatch::rejectNotifications(function (Notification $notification) {
    return $notification->channel === 'database';
});
过滤所有通知
bash
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
按渠道过滤
php
use Laravel\Nightwatch\Records\Notification;

Nightwatch::rejectNotifications(function (Notification $notification) {
    return $notification->channel === 'database';
});

Outgoing HTTP Requests

外部HTTP请求

Filter all outgoing requests:
bash
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
Filter by URL:
php
use Laravel\Nightwatch\Records\OutgoingRequest;

Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
    return str_contains($request->url, 'analytics.example.com');
});
过滤所有外部请求
bash
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
按URL过滤
php
use Laravel\Nightwatch\Records\OutgoingRequest;

Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
    return str_contains($request->url, 'analytics.example.com');
});

Queued Jobs

队列任务

Filter specific jobs:
php
use Laravel\Nightwatch\Records\QueuedJob;

Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
    return $job->name === 'App\Jobs\LowPriorityJob';
});
过滤特定任务
php
use Laravel\Nightwatch\Records\QueuedJob;

Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
    return $job->name === 'App\Jobs\LowPriorityJob';
});

Decoupling Job Sampling

任务采样解耦

Sample jobs independently from parent contexts:
php
use Illuminate\Support\Facades\Queue;

public function boot(): void
{
    Queue::before(fn () => Nightwatch::sample(rate: 0.5));
}

独立于父上下文对任务进行采样:
php
use Illuminate\Support\Facades\Queue;

public function boot(): void
{
    Queue::before(fn () => Nightwatch::sample(rate: 0.5));
}

Redaction Configuration

脱敏配置

Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
脱敏用于修改捕获的数据,移除或模糊敏感信息。与过滤不同,脱敏会保留事件但清理其内容。

Request Redaction

请求脱敏

Redact sensitive headers (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
bash
undefined
脱敏敏感请求头(自动脱敏:Authorization、Cookie、X-XSRF-TOKEN):
bash
undefined

Customize redacted headers

自定义脱敏请求头

NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key

**Redact request payloads** (disabled by default):

```bash
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key

**脱敏请求负载**(默认禁用):

```bash

Enable payload capture

启用负载捕获

NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true

Customize redacted fields

自定义脱敏字段

NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card

**Programmatic redaction**:

```php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Request;

Nightwatch::redactRequests(function (Request $request) {
    $request->url = str_replace('secret', '***', $request->url);
    $request->ip = preg_replace('/\d+$/', '***', $request->ip);
});
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card

**程序化脱敏**:

```php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Request;

Nightwatch::redactRequests(function (Request $request) {
    $request->url = str_replace('secret', '***', $request->url);
    $request->ip = preg_replace('/\d+$/', '***', $request->ip);
});

Query Redaction

查询脱敏

php
use Laravel\Nightwatch\Records\Query;

Nightwatch::redactQueries(function (Query $query) {
    $query->sql = str_replace('secret_token', '***', $query->sql);
});
php
use Laravel\Nightwatch\Records\Query;

Nightwatch::redactQueries(function (Query $query) {
    $query->sql = str_replace('secret_token', '***', $query->sql);
});

Cache Redaction

缓存脱敏

php
use Laravel\Nightwatch\Records\CacheEvent;

Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
    $cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
});
php
use Laravel\Nightwatch\Records\CacheEvent;

Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
    $cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
});

Command Redaction

命令脱敏

php
use Laravel\Nightwatch\Records\Command;

Nightwatch::redactCommands(function (Command $command) {
    $command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
});
php
use Laravel\Nightwatch\Records\Command;

Nightwatch::redactCommands(function (Command $command) {
    $command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
});

Exception Redaction

异常脱敏

php
use Laravel\Nightwatch\Records\Exception;

Nightwatch::redactExceptions(function (Exception $exception) {
    $exception->message = str_replace('secret', '***', $exception->message);
});
php
use Laravel\Nightwatch\Records\Exception;

Nightwatch::redactExceptions(function (Exception $exception) {
    $exception->message = str_replace('secret', '***', $exception->message);
});

Mail Redaction

邮件脱敏

php
use Laravel\Nightwatch\Records\Mail;

Nightwatch::redactMail(function (Mail $mail) {
    $mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
});
php
use Laravel\Nightwatch\Records\Mail;

Nightwatch::redactMail(function (Mail $mail) {
    $mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
});

Outgoing Request Redaction

外部请求脱敏

php
use Laravel\Nightwatch\Records\OutgoingRequest;

Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
    $outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
});
php
use Laravel\Nightwatch\Records\OutgoingRequest;

Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
    $outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
});