Download the PHP package uengage.io/php-logger without Composer

On this page you can find all versions of the php package uengage.io/php-logger. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package php-logger

uengage.io/php-logger

Structured observability logging for uEngage platform services. Write logs to a local file, POST them over HTTP, or emit to stdout - same JSON schema regardless of transport.


Table of Contents


Overview

uengage/logger provides a single Logger class with four log-level methods (info, error, debug, warn). On initialization you choose a transport:

Transport How it works Best for
file Appends NDJSON lines to {basePath}/application/{product}.log EC2/server - CloudWatch Agent, Datadog Agent, or Fluentd ships the file
http POSTs JSON to an HTTP endpoint Environments without a cloud agent
stdout Writes one NDJSON line per entry to php://stdout Lambda (Bref / custom runtime), Docker

In addition to the primary transport, a Logger can carry an optional debug sink - an always-on, minLevel-independent channel that ships only DEBUG entries to S3 via Amazon Kinesis Data Firehose. See Debug Sink (Firehose → S3).

The log schema is identical to the Node.js @uengage/logger package - uniform cross-service log analysis.


Requirements


Installation


Quick Start

File transporter (server / EC2)

HTTP transporter (no cloud agent)

Stdout transporter (Lambda / Docker)


Log Schema


Initialization

Validates synchronously; throws \InvalidArgumentException immediately if anything required is missing or invalid.

Config Reference


Transporters

File Transporter

Appends one NDJSON line per entry to {basePath}/application/{product}.log. The directory is created automatically; all services for the same product on a host share one file.

File rotation - when the file reaches maxFileSizeBytes:

Configure your cloud agent to watch application/edge.log* to pick up rotated files. Writes use FILE_APPEND | LOCK_EX - safe for concurrent PHP-FPM workers.

Files are created mode 0664, dropping the usual umask 022 default so the log is at least group-writable. This is necessary but not sufficient for cross-user appends: 0664 grants write to the file's group, and the group is fixed at creation (the creator's egid, or the directory's group if it is setgid). Whether another user can then append depends on that user being in that group — which the library cannot arrange. If your fpm user and your cron user don't share the log's group, you still need an ops-side fix.

Write failures are rate-limited (since 2.0.0 — see CHANGELOG). On a failed write (typically an unwritable path) the transporter reports once to error_log(), then stops attempting writes for 60 s before probing the path again. The count of dropped entries rides along on the next report, on the first successful write after recovery, and on destroy(). file_put_contents()'s own E_WARNING is suppressed and its reason recovered via error_get_last(), so a tripped breaker costs exactly one stderr line rather than two — PHP's plus ours.

Note the trade: entries in that 60 s window are dropped without an attempt, so a path fixed mid-window isn't picked up until the next probe.

The cooldown lives on the transporter instance, which is what the bound is relative to:

Runtime Instance lifetime Effective bound on a persistently broken path
php-fpm / mod_php one request one stderr line per request
warm Lambda container, CLI daemon, Swoole/RoadRunner many units of work ~one line per minute

Either way the per-response cost is capped, which is what prevents the 502. Don't write "~1/minute" into alerting copy for a php-fpm deployment.

This matters under php-fpm: error_log() output goes to FCGI stderr, which nginx buffers in the same space as the response headers. Reporting every failed entry let a request that logs tens of entries overflow fastcgi_buffer_size, and nginx answered 502 upstream sent too big header even though PHP had completed the work. Capping it at one line per failure window keeps a broken log path from taking the endpoint down. Raising fastcgi_buffer_size on the nginx side is still worthwhile defence in depth.


HTTP Transporter

POSTs log entries to an HTTP endpoint via cURL.


Stdout Transporter

Writes one NDJSON line per entry to php://stdout. No config knobs.

Best for AWS Lambda (Bref / custom PHP runtime) and Docker - the runtime captures stdout into CloudWatch Logs or your log-aggregation service. Uses php://stdout rather than the STDOUT constant, which is undefined under PHP-FPM and most Lambda runtime adapters.


Debug Sink (Firehose → S3)

DEBUG logs are high-volume and rarely belong in the primary observability stream. The debug sink is a dedicated, always-on channel that ships only DEBUG-level entries to S3 via Amazon Kinesis Data Firehose - separately from, and in addition to, the primary transport.

Behaviour

Aspect Detail
Levels captured DEBUG only. info/warn/error never reach the sink.
minLevel Bypassed. DEBUG reaches the sink even when the primary minLevel (e.g. warn) drops it.
Delivery In-memory batched, one record per entry. send() buffers the entry; nothing is sent until flush, which ships every buffered NDJSON line as its own Firehose record in aggregated PutRecordBatch calls (N entries still collapse into one HTTP call). One record = one JSON object is a hard requirement of the stream's dynamic partitioning — multi-object records are silently mis-routed to the errors/ prefix, invisible to Athena.
Flush triggers (1) process shutdown when autoFlush is on (EC2/PHP-FPM), (2) buffer reaching maxBufferBytes (default 4 MiB), (3) explicit $logger->flush() / $logger->destroy(). See Flushing.
Timeout timeoutMs (default 200 ms), connect + total, per batch call. SDK retries disabled so an outage fails fast.
Failure handling Two hops. Entries a PutRecordBatch fails to ship (exception, timeout, or per-record reject) are re-sent to the SQS backup queue (on by default) and replayed into the stream by the platform redrive Lambda. Only when BOTH hops fail is one summary ERROR (code: FIREHOSE_DELIVERY_FAILED, context.dropped_entries) emitted to the primary transport + error_log(). Never throws. A transport failure also opens a per-hop circuit breaker (breakerCooldownSeconds, default 30 s; 0 disables): while open, that hop is skipped entirely, so an outage costs one failed call per cooldown window per host — not timeout×retries on every request (which would exhaust the FPM worker pool).
Backup backup.queueUrl defaults to the prod redrive queue (same convention as assumeRoleArn); override for dev/uat or set '' to disable. Looser budget than the put — backup.timeoutMs (default 2000 ms) with backup.maxRetries (default 1) — because it only runs on the already-slow failure path. Shares the Firehose credentials (the put-role carries the sqs:SendMessage grant).
Billing One entry = one Firehose record, so Firehose's 5 KB per-record rounding applies per entry — unchanged from 2.x, which also sent one record per entry. Batching cuts HTTP calls, not ingested bytes. Records cannot be aggregated to avoid the rounding: the stream's dynamic partitioning requires one JSON object per record.
Credentials assumeRoleArn (default: prod platform put-role) > explicit accessKeyId/secretAccessKey > SDK default chain. Set assumeRoleArn => '' to force the default chain.

Durability: at-least-once while the process lives. A Firehose failure is absorbed by the SQS backup and replayed, so an outage of either service alone loses nothing (expect occasional duplicates — dedupe downstream on trace_id). Entries are still lost if the process dies hard (OOM / segfault / SIGKILL) before a flush, if a single entry exceeds the 248 KiB SQS body cap, or if Firehose AND SQS fail on the same flush — that last case is what the fallback ERROR reports. Two caveats: both hops share one credential provider, so a failed assume-role kills Firehose and SQS with the same error (the hops are only independent for service-side failures); and the backup queue auto-recovers from blips of roughly 20 minutes (8 receives × 180 s visibility) — beyond that, messages dead-letter and need a console redrive, so the 7-day queue retention is a forensics window, not the recovery window.

Dependency: the Firehose sink requires aws/aws-sdk-php (composer require aws/aws-sdk-php). If it is not installed, constructing a logger with a firehose sink throws a clear \RuntimeException at boot rather than silently dropping logs.

Flushing: EC2 vs Lambda

Because entries are batched in memory, something has to flush them. This differs by runtime:

EC2 / PHP-FPM / CLI — leave autoFlush on (default). The transporter registers a register_shutdown_function that flushes when the request/script ends, so you don't call anything. Two refinements:

AWS Lambda — safe by default: when AWS_LAMBDA_FUNCTION_NAME is set and autoFlush is not configured, the sink flushes after every send() (the execution environment — and its buffer — persists across invocations, so the shutdown-function flush would only run on environment teardown, mixing invocations and losing data). Batching on Lambda is opt-in: set autoFlush => false and flush at the end of every invocation in a finally:

flush() is idempotent, so an extra call (or a destroy() afterwards) is harmless.

Cross-account: legacy producers → platform-account S3

The debug-log bucket + Firehose stream live in the platform account, but producers run in the legacy account. Firehose has no resource-based policy for direct PutRecord, so cross-account access is via AssumeRole, not a grant on the stream:

Credential caching (important for PHP-FPM): PHP is shared-nothing, so without a cross-request cache every web request would perform its own STS AssumeRole call. The transporter caches the assumed credentials in APCu when ext-apcu is present (shared across FPM workers on the host), collapsing that to ~one STS call per host per hour. Install ext-apcu on producer hosts - without it the transporter falls back to per-request memoization (per-request STS on PHP-FPM; fine on warm Lambda, where the process persists across invocations).

Firehose → S3 setup: the DebugLogFirehose CDK construct provisions the stream (GZIP → S3, date-partitioned), delivery role, and cross-account put-role. Records are newline-delimited JSON, so the S3 objects are directly queryable with Athena / S3 Select.

The same { type, config } shape is accepted, so a debug sink can also target file, http, or stdout - but firehose is the intended production path.


Log Methods

Method Signature

Log Options Reference


Level Filtering

Set minLevel to suppress low-priority logs without changing call sites (default: 'warn'):

minLevel DEBUG INFO WARN ERROR
'warn' (default) - - ✓ ✓
'info' - ✓ ✓ ✓
'error' - - - ✓
'debug' ✓ ✓ ✓ ✓

Graceful Shutdown

Transport Action needed
file None - writes are synchronous.
http (immediate, batchSize=1) None - each call fires synchronously.
http (batch, default batchSize=5) Call $logger->destroy() before exit to flush the queue.
stdout None - writes are synchronous.
debugSink (firehose) EC2/PHP-FPM: none (autoFlush flushes at shutdown). Lambda: set autoFlush => false and $logger->flush() per invocation - see Flushing.

Register shutdown for HTTP batch mode:


CodeIgniter 2 Integration

Prerequisite - load Composer autoloader

CI2 does not load Composer's autoloader by default. Add one of the following:

Option A - application/config/config.php (recommended):

Option B - index.php (before the CI bootstrap):


Logger_service library

Logger_service acts as a lazy factory for the logger. Load it once per controller; it caches one Logger instance per service name for the lifetime of the request.

1. Load the library in your controller

2. Get a logger and write a log

3. Use from a library / helper (no $this)

How it works internally

What Detail
Factory method get(string $service, string $component = 'edge-server')
Caching One Logger instance per "service:component" key per request
Log file loggerlogs/edge-{service}.log
Min level warn in production, debug in all other environments
Fallback If Logger construction fails, a NullLogger is returned - your code never throws

Tip - dynamic log level


Flushing HTTP batch mode in CI2

Register destroy() via a post_system hook:

Or via register_shutdown_function in your base controller:


CodeIgniter 4 Integration

CI4 includes Composer autoloading out of the box - no manual require needed.

Register as a CI4 Service (app/Config/Services.php):

Use in any Controller, Model, or Library:

Flushing HTTP batch mode - register destroy() in a CI4 After-filter or your BaseController destructor:


PHP-Specific Notes

Behaviour PHP implementation Note
Non-blocking writes Synchronous - writes complete inline PHP has no event loop
flushIntervalMs Accepted in config but no-op Use destroy() instead
UUID generation openssl_random_pseudo_bytes (preferred) or mt_rand fallback
Deep clone json_decode(json_encode($val), true) Equivalent to JS structuredClone()
Timestamp gmdate() + microtime(true) ms Produces Z suffix matching ISO 8601 / Node output
Error output error_log() Visible in /var/log/php_errors.log or Apache/Nginx error log
Concurrent file writes file_put_contents(..., FILE_APPEND \| LOCK_EX) Prevents torn writes from concurrent FPM workers

Examples

Business event - order placed

Engineering error - payment gateway timeout

Warning - rate limit approaching

Debug - database query


Architecture

Error contract: every transporter catches all internal errors and writes to error_log(). A logging failure never throws to the caller. FileTransporter additionally rate-limits its own reporting to one line per 60 s failure window — see File Transporter for why that bound exists.


Running Tests

Expected output:


All versions of php-logger with dependencies

PHP Build Version
Package Version
Requires php Version >=7.1
ext-curl Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package uengage.io/php-logger contains the following files

Loading the files please wait ...