Documentation forSolarWinds Observability SaaS

Ship PHP application logs (Papertrail)

You can ship PHP application logs directly to Papertrail over HTTPS, using Monolog. The setup adds one handler class to Monolog. This allows the following:

  • Each log record shows the correct System, Program, and Severity in the Logs Explorer.

  • Log records keep the plain-text message, with context appended as JSON only when present.

  • Multiline records arrive as one event.

  • Log records are sent in batches over port 443, so the setup will work behind HTTP-only firewalls.

To get a destination and token in Papertrail, add a new log destination. The ingestion token is generated along with the destination. Use the collector endpoints for your account's region:

  • HTTPS: https://logs.collector.<REGION>.cloud.solarwinds.com/v1/logs/bulk

Replace <REGION> with the data center your organization uses: na-01, eu-01, or ap-01.

How Papertrail fills System, Program, and Severity

The Papertrail Logs Explorer is syslog-shaped. It shows the source in the System column, the application in the Program column, and the Severity of each event. The handler on this page wraps every log record in a standard RFC 5424 syslog header and posts the batch to the HTTPS bulk endpoint with Content-Type: application/syslog-frames. The collector reads the header of each record:

Logs Explorer category Source PHP value
System Syslog HOSTNAME Server host name (gethostname())
Program Syslog APP-NAME The appName you pass to the handler
Severity Syslog PRI Monolog log level
Message Syslog MSG Log message, context as JSON, exception stack trace

Each record is prefixed with its length in bytes (octet-counted framing), so line breaks inside a message do not split it into several events.

Ship PHP application logs over HTTPS

Requirements

  • PHP 8.1 or later

  • Monolog 3 (composer require monolog/monolog). (Included in Symfony apps through MonologBundle.)

  • PHP curl extension (installed on almost every PHP host)

  • Outbound HTTPS (port 443) to logs.collector.<REGION>.cloud.solarwinds.com

Step 1: Add the handler

Create src/Logging/SwoLogHandler.php:

<?php

namespace App\Logging;

use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
use Throwable;

class SwoLogHandler extends AbstractProcessingHandler
{
    private array $frames = [];
    private int $bytes = 0;

    public function __construct(private string $region, private string $token, private string $appName, int|string|Level $level = Level::Debug, bool $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->appName = str_replace(' ', '-', $appName);
    }

    protected function write(LogRecord $record): void
    {
        // Plain-text message, then context as JSON, then PHP's own multi-line stack trace.
        $context = $record->context + $record->extra;
        $exception = $context['exception'] ?? null;
        unset($context['exception']);

        $text = $record->message;
        if ($context) {
            $text .= ' '.json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR);
        }
        if ($exception instanceof Throwable) {
            $text .= "\n".$exception;
        }

        // The syslog header sets Severity, System and Program. The length prefix keeps multi-line messages in one event.
        $message = sprintf('<%d>1 %s %s %s %d %s - %s',
            8 + $record->level->toRFC5424Level(),
            $record->datetime->format('Y-m-d\TH:i:s.uP'),
            gethostname(), $this->appName, getmypid(), $record->channel, $text);

        $this->frames[] = strlen($message).' '.$message;
        $this->bytes += strlen($message);

        if (count($this->frames) >= 100 || $this->bytes > 4_000_000) {
            $this->flush();
        }
    }

    public function flush(): void
    {
        if (! $this->frames) {
            return;
        }

        $ch = curl_init("https://logs.collector.{$this->region}.cloud.solarwinds.com/v1/logs/bulk");
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => implode('', $this->frames),
            CURLOPT_HTTPHEADER => ["Authorization: Bearer {$this->token}", 'Content-Type: application/syslog-frames'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 5,
        ]);
        curl_exec($ch);

        if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) !== 202) {
            error_log('SWO log delivery failed: HTTP '.curl_getinfo($ch, CURLINFO_RESPONSE_CODE).' '.curl_error($ch));
        }

        $this->frames = [];
        $this->bytes = 0;
    }

    public function close(): void
    {
        $this->flush();
    }

    // Long-running workers call reset() between jobs; Symfony does it automatically.
    public function reset(): void
    {
        $this->flush();
        parent::reset();
    }
}

Symfony autoloads App\ from src/ already. In other projects, add "autoload": {"psr-4": {"App\\": "src/"}} to composer.json and run composer dump-autoload, or require the file directly.

Step 2: Register the handler (choose your framework)

Plain PHP

Add the handler to your Monolog logger:

<?php

require __DIR__.'/vendor/autoload.php';

use App\Logging\SwoLogHandler;
use Monolog\ErrorHandler;
use Monolog\Logger;
use Monolog\Processor\PsrLogMessageProcessor;

$log = new Logger('app');
$log->pushHandler(new SwoLogHandler(
    region: getenv('SWO_REGION'),
    token: getenv('SWO_TOKEN'),
    appName: 'my-app',
));
$log->pushProcessor(new PsrLogMessageProcessor());

// Optional: also log uncaught exceptions and PHP errors.
ErrorHandler::register($log);

$log->info('Hello from PHP', ['order_id' => 1234]);

try {
    throw new RuntimeException('Card declined');
} catch (RuntimeException $e) {
    $log->error('Payment failed', ['exception' => $e]);
}

Set SWO_REGION and SWO_TOKEN as environment variables. The logger name (app) is sent as the syslog message ID and is searchable as syslog.msgid.

Symfony

Register the handler as a service in config/services.yaml. Add the App\Logging\SwoLogHandler entry under the existing services: key:

services:
    # ... existing service definitions ...

    App\Logging\SwoLogHandler:
        arguments:
            $region: '%env(SWO_REGION)%'
            $token: '%env(SWO_TOKEN)%'
            $appName: 'my-app'
            $level: 'info'
        calls:
            - pushProcessor: [!service { class: Monolog\Processor\PsrLogMessageProcessor }]

Add it to Monolog in config/packages/monolog.yaml. Put handlers under the existing top-level monolog: key. A second monolog: key fails with "Duplicate key."

monolog:
    handlers:
        swo:
            type: service
            id: App\Logging\SwoLogHandler
            channels: ['!deprecation']

Add the region and token to .env.local (or to your secrets), then run php bin/console cache:clear:

SWO_REGION=<REGION>
SWO_TOKEN=<TOKEN>

Notes:

  • The pushProcessor call fills placeholders such as {route} in Symfony's messages. MonologBundle does not add it to service handlers on its own.

  • channels: ['!deprecation'] keeps deprecation notices out. Remove it to send everything.

  • The Symfony log channel (app, request, security, ...) is searchable as syslog.msgid.

Step 3: Verify

The verification method depends on the framework you used:

  • Plain PHP: Run the script from Step 2. Search the Logs Explorer for Hello from PHP.

  • Symfony: Open any page of your app and search the Logs Explorer for Matched route.

The System column shows your server's host name and Program shows my-app. Errors appear as one event with the full stack trace.

What arrives in the Logs Explorer

The Logs Explorer will show events:

The following searchable attributes are extracted from each event:

Attribute Value
syslog.host, syslog.appname System and Program
syslog.msgid Monolog channel, for example app or request
syslog.procId PHP process ID
json.* Each context field, for example json.order_id:1234

Troubleshooting

Symptom Likely cause What to do
SWO log delivery failed: HTTP 401 in the PHP error log Wrong token, or the token belongs to a different region Copy the token again from the log destination and check SWO_REGION.
SWO log delivery failed: HTTP 0 Resolving timed out, and requests are slow SWO_REGION contains an invalid value Use your account's region (for example, na-01 or eu-01)
Messages show placeholders such as {route} No PsrLogMessageProcessor on the handler Add the $log->pushProcessor(...) (plain PHP) or the pushProcessor call (Symfony)
Symfony: Duplicate key "monolog" A second monolog: key was added to monolog.yaml Move handlers under the existing monolog: key.
Class "App\Logging\SwoLogHandler" not found App\ is not autoloaded from src/ Add the PSR-4 autoload entry and run composer dump-autoload.

Fallback: Forward via a syslog daemon

If your application cannot connect directly to the Papertrail collector (for example, a strict outbound firewall blocks ports 6514 and 443), write logs to a local file and use the host's syslog daemon to forward them to Papertrail over TLS. Papertrail supports rsyslog on Linux and NXlog on Windows for this purpose. See Send logs using syslog (Papertrail) for configuration instructions.

The scripts are not supported under any SolarWinds support program or service. The scripts are provided AS IS without warranty of any kind. SolarWinds further disclaims all warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The risk arising out of the use or performance of the scripts and documentation stays with you. In no event shall SolarWinds or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the scripts or documentation.