Implementing Elastic Common Schema in PHP with PECS: A Comprehensive Guide
This article explains why consistent logging structures are essential for growing teams, introduces the Elastic Common Schema (ECS) and the PECS PHP library that fully supports ECS, and provides practical code examples for creating ECS‑compatible logs and integrating PECS with Monolog.
In small teams, logging structures can vary, but as teams grow a robust and consistent logging layer becomes crucial for developer efficiency and cross‑department readability.
When recording client IP addresses, several field naming conventions exist, such as src , client_ip , apache2.access.remote_ip , context.user.ip , and src_ip , highlighting the need for a standardized, compact approach across platforms.
Challenges and Solutions
Achieving logging consistency remains challenging; it requires defining a logging schema and ensuring widespread adoption within the team. Naming variables is especially difficult, demanding diverse knowledge to design a standard method across architectural domains.
Elasticsearch Common Schema (ECS) is the recommended data model for Elasticsearch, offering a standardized structure for storing and retrieving data. Implementing ECS from scratch in PHP is effort‑intensive, and existing PHP SDKs cover only a limited set of fields.
PECS (PHP Elastic Common Schema) addresses this gap as an open‑source project that brings full ECS support to the PHP ecosystem.
PECS Design Goals
Simple and intuitive API.
Minimal documentation required to start using.
Type hints and mechanisms to prevent misuse.
Comprehensive support for all ECS fields.
Easy extensibility for custom field classes and enums.
Targeted at PHP developers working with ECS.
PECS converts the ECS specification into JSON configuration and uses a built‑in generator to create PHP classes with native type hints, reducing the risk of misuse. The package is extensible, allowing instantiation of fields and rendering them in the expected ECS format.
PECS provides an EcsFieldsCollection class for building ECS fields. Example usage:
<code>use PECS\EcsFieldsCollection;
// Create a collection
$collection = new EcsFieldsCollection([
new Log(
filePath: 'app/Http/Controllers/Controller.php',
level: 'info',
logger: 'name',
originFileLine: 42,
originFileName: 'Controller.php',
originFunction: 'index',
),
new Client(
ip: '10.42.42.42',
geo: new Geo(
cityName: 'Amsterdam',
continentCode: 'EU',
continentName: 'Europe',
countryIsoCode: 'NL',
countryName: 'Netherlands',
location: new GeoPoint(52.37403, 4.88969),
),
user: new User(
id: 'e125a612-899e-11ee-b9d1-0242ac120002',
name: 'hamid',
roles: (new ValueList())->push('admin')->push('user'),
)
),
new Os(
kernel: '4.19.0-6-amd64',
name: 'Arch',
platform: 'x86_64',
type: OsType::LINUX
),
]);
// Render the collection
$output = $collection->render();
</code>The rendered output demonstrates the JSON representation of the specified fields:
<code>{
"log": {
"file": {"path": "app/Http/Controllers/Controller.php"},
"level": "info",
"logger": "name",
"origin": {
"file": {"line": 42, "name": "Controller.php"},
"function": "index"
}
},
"client": {
"ip": "10.42.42.42",
"geo": {
"city_name": "Amsterdam",
"continent_code": "EU",
"continent_name": "Europe",
"country_iso_code": "NL",
"country_name": "Netherlands",
"location": {"lat": 52.37403, "lon": 4.88969}
},
"user": {
"id": "e125a612-899e-11ee-b9d1-0242ac120002",
"name": "hamid",
"roles": ["admin", "user"]
}
}
}
</code>Integration
PECS acknowledges that pure PHP logging is no longer typical and therefore ships as a Monolog handler, enabling seamless integration with frameworks like Symfony and Laravel that rely on Monolog.
Example of using PECS with Monolog:
<code>use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use PECS\EcsFormatter;
use PECS\Event;
$log = new Logger('my_app');
$handler = new StreamHandler('php://stdout');
$handler->setFormatter(new EcsFormatter());
$log->pushHandler($handler);
$log->info('message', [
new Event(action: 'test event'),
]);
</code>This integration allows developers to log ECS‑compatible events directly from Symfony or Laravel applications.
In summary, PECS offers a comprehensive solution for implementing the Elastic Common Schema in PHP, providing fully typed classes, easy extensibility, and seamless Monolog integration to ensure consistent, structured logging across diverse platforms.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.