High-performance API performing logging for PHP applications into files or SysLog

Overview

Logging API

Table of contents:

About

This API is a skeleton (requires binding by developers) logging system built on principles of simplicity and flexibility. Unlike Monolog, the industry standard in our days, it brings no tangible performance penalties and has near-zero learning curve just by keeping complexity to a minimum while offering you the ability to extend functionalities.

diagram

The whole idea of logging is reduced to just three steps:

  • configuration: setting up an XML file where one or more loggers are set for each development environment
  • binding points: binding user-defined components defined in XML/code to API prototypes in order to gain necessary abilities
  • logging: creating a Wrapper instance based on above XML and using it to log

API is fully PSR-4 compliant, only requiring PHP8.1+ interpreter and SimpleXML extension. To quickly see how it works, check:

  • installation: describes how to install API on your computer, in light of steps above
  • unit tests: API has 100% Unit Test coverage, using UnitTest API instead of PHPUnit for greater flexibility
  • example: shows a deep example of API functionality based on unit test for Wrapper

All classes inside belong to Lucinda\Logging namespace!

Configuration

To configure this API you must have a XML with a loggers tags inside:

<loggers path="...">
	<{ENVIRONMENT}>
		<logger class="..." {OPTIONS}/>
		...
	</{ENVIRONMENT}>
	...
</loggers>

Where:

  • loggers: (mandatory) holds global logging policies.
    • {ENVIRONMENT}: name of development environment (to be replaced with "local", "dev", "live", etc)

Example:

<loggers>
    <local>
        <logger class="Lucinda\Logging\Driver\File\Wrapper" path="messages" format="%d %v %e %f %l %m %u %i %a" rotation="Y-m-d"/>
    </local>
    <live>
        <logger class="Lucinda\Logging\Driver\File\Wrapper" path="messages" format="%d %v %e %f %l %m %u %i %a" rotation="Y-m-d"/>
        <logger class="Lucinda\Logging\Driver\SysLog\Wrapper" application="unittest" format="%v %e %f %l %m %u %i %a"/>
    </live>
</loggers>

Binding Points

In order to remain flexible and achieve highest performance, API takes no more assumptions than those absolutely required! It offers developers instead an ability to bind to its prototypes via XML:

XML Attribute @ Tag Class Prototype Ability Gained
class @ logger AbstractLoggerWrapper Registers a logger

API already has following AbstractLoggerWrapper implementation embedded:

But developers can bind their own (check: How to Bind a Custom Logger)

Logging

Now that XML is configured, you can get a logger to save and use later on whenever needed by querying Wrapper:

$object = new Lucinda\Logging\Wrapper(simplexml_load_file(XML_FILE_NAME), DEVELOPMENT_ENVIRONMENT);
$logger = $object->getLogger();

Logger returned is a Logger that hides complexity of logger(s) underneath through a common interface centered on logging operations. Each Logger must have a AbstractLoggerWrapper whose job is to generate it based on info in XML.

NOTE: because XML parsing is somewhat costly, it is recommended to save $logger somewhere and reuse it throughout application lifecycle.

Installation

First choose a folder where API will be installed then write this command there using console:

composer require lucinda/logging

Then create a configuration.xml file holding configuration settings (see configuration above) and a index.php file (see logging above) in project root with following code:

require(__DIR__."/vendor/autoload.php");
$object = new Lucinda\Logging\Wrapper(simplexml_load_file("configuration.xml"), "local");
$logger = $object->getLogger();
$logger->info("test");

Above has logged a "test" message with LOG_INFO priority in messages__YYYY-MM-DD.log file if same loggers tag as in example above is used.

Unit Tests

For tests and examples, check following files/folders in API sources:

NOTE: on first run only, test.php will fail on syslog tests but from that moment on it will consistently pass

Reference Guide

Interface Logger

Logger interface provides blueprints for level-oriented logging using following methods:

Method Arguments Returns Description
emergency \Throwable $exception void logs a \Throwable using LOG_ALERT priority
alert \Throwable $exception void logs a \Throwable using LOG_CRIT priority
critical \Throwable $exception void logs a \Throwable using LOG_ERR priority
error \Throwable $exception void logs a \Throwable using LOG_WARNING priority
warning string $message void logs a string using LOG_WARNING priority
notice string $message void logs a string using LOG_NOTICE priority
debug string $message void logs a string using LOG_DEBUG priority
info string $message void logs a string using LOG_INFO priority

Usage example:

https://github.com/aherne/php-logging-api/blob/master/drivers/File/Logger.php

Abstract Class LoggerWrapper

AbstractLoggerWrapper abstract class implements conversion of data in XML to a Logger instance via following public methods:

Method Arguments Returns Description
__construct SimpleXMLElement $xml void Reads XML and delegates to setLogger method
getLogger void Logger Gets Logger generated based on XML

and following prototype method that needs to be implemented by developers:

Method Arguments Returns Description
setLogger SimpleXMLElement $xml void Reads XML and generates a Logger object

Usage example:

https://github.com/aherne/php-logging-api/blob/master/drivers/File/Wrapper.php

Specifications

Some guides helping developers to get the best of this API:

How are log lines formatted

As one can see above, logger tags whose class is Driver\File\Wrapper and Driver\SysLog\Wrapper support a format attribute whose value can be a concatenation of:

  • %d: current date using Y-m-d H:i:s format.
  • %v: syslog priority level constant value matching to Logger method called.
  • %e: name of thrown exception class ()
  • %f: absolute location of file that logged message or threw a Throwable
  • %l: line in file above where message was logged or Throwable/Exception was thrown
  • %m: value of logged message or Throwable message
  • %e: class name of Throwable, if log origin was a Throwable
  • %u: value of URL when logging occurred, if available (value of $_SERVER["REQUEST_URI"])
  • %a: value of USER AGENT header when logging occurred, if available (value of $_SERVER["HTTP_USER_AGENT"])
  • %i: value of IP when logging occurred, if available (value of $_SERVER["REMOTE_ADDR"])

Example:

<logger format="%d %f %l" .../>

How to bind a custom logger

Let us assume you want to bind a new SQL logger to this API. First you need to implement the logger itself, which must extend Logger and implement its required log method:

class SQLLogger extends Lucinda\Logging\Logger
{
    private $schema;
    private $table;

    public function __construct(string $schema, string $table)
    {
        $this->schema = $schema;
        $this->table = $table;
    }

    protected function log($info, int $level): void
    {
        // log in sql database based on schema, table, info and level
    }
}

Now you need to bind logger above to XML configuration. To do so you must create another class extending AbstractLoggerWrapper and implement its required setLogger method:

class SQLLoggerWrapper extends Lucinda\Logging\AbstractLoggerWrapper
{
    protected function setLogger(\SimpleXMLElement $xml): Lucinda\Logging\Logger
    {
        $schema = (string) $xml["schema"];
        $table = (string) $xml["table;
        return new SQLLogger($schema, $table);
    }
}

In that case if "psr-4" attribute in composer.json associates "Lucinda\Project\" with "src/" folder then SQLLoggerWrapper must be placed in src/Loggers folder then you finally need to bind it to XML:

<loggers>
    <local>
        <logger class="Lucinda\Project\Loggers\SQLLoggerWrapper" table="logs" schema="logging_local"/>
    </local>
    <live>
        <logger class="Lucinda\Project\Loggers\SQLLoggerWrapper" table="logs" schema="logging_production"/>
    </live>
</loggers>
You might also like...
Small package that can helps in debugging with API logs for Laravel Project.

Rest APIs Logger This is a small package that can helps in debugging with API logs. Installation Install the package via composer composer require tfs

Small laravel package for viewing api logs which can be used in debugging.
Small laravel package for viewing api logs which can be used in debugging.

This is a small package that can helps in debugging api logs. It can log request method, url, duration, request payload, which models are retrieved, controller and method.

An effective,fast,stable log extension for PHP
An effective,fast,stable log extension for PHP

SeasLog An effective,fast,stable log extension for PHP @author Chitao.Gao [[email protected]] Documentation On php.net 中文文档 Synopsis Why use seaslog What

Simple PHP Logger. Composer package

Basic PHP Logger 📝 Simple logger. Composer package.

ChromePhp - a PHP library for the Chrome Logger Google Chrome extension

ChromePhp - a PHP library for the Chrome Logger Google Chrome extension

Leaf's very own high-speed, high-performance server
Leaf's very own high-speed, high-performance server

[WIP] Leaf Eien Server Eien is Leaf's implementation of a high-speed, high-performance server based on powerful tools like Open Swoole and Swoole. Eie

High performance view templating API for PHP applications using tags & expressions inspired by Java JSTL and C compiler

View Language API Table of contents: About Expressions Tags Configuration Compilation Installation Unit Tests Examples Reference Guide About This API

Biny is a tiny, high-performance PHP framework for web applications

Biny is high performance. Framework comes default with response time of less than 1ms. Stand-alone QPS easily up to 3000.

A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load.

A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load. Well implemented, it can drops the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful.

Stackdriver Monitoring provides visibility into the performance, uptime, and overall health of cloud-powered applications.

Stackdriver Monitoring API documentation NOTE: This repository is part of Google Cloud PHP. Any support requests, bug reports, or development contribu

PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

Engine for performing and rendering text diffs

Text_Diff Engine for performing and rendering text diffs This package provides a text-based diff engine and renderers for multiple diff output formats

Provides an easy interface for performing Hyper-Text Transfer Protocol (HTTP) requests

laminas-http provides the HTTP message abstraction used by laminas-mvc, and also provides an extensible, adapter-driven HTTP client library.

The Pantheon CLI — a standalone utility for performing operations on the Pantheon Platform

terminus : Pantheon's Command-Line Interface Status About Terminus is Pantheon's Command Line Interface (CLI), providing at least equivalent functiona

This package is for centralized logging of multiple Laravel application into one connection.

Laralogs This package is for centralized logging of multiple Laravel application into one connection. Installation You can install the package via com

The package provides the ability to write logs into the database synchronously or asynchronously, along with other logging channels.

Laravel database log channel The package provides the ability to write logs into the database synchronously or asynchronously, along with other loggin

Best logging support into Nette Framework (@nette)
Best logging support into Nette Framework (@nette)

Website 🚀 contributte.org | Contact 👨🏻‍💻 f3l1x.io | Twitter 🐦 @contributte Usage To install the latest version of contributte/monolog use Compose

Propel2 is an open-source high-performance Object-Relational Mapping (ORM) for modern PHP

Propel2 Propel2 is an open-source Object-Relational Mapping (ORM) for PHP. Requirements Propel uses the following Symfony Components: Config Console F

Owner
Lucian Gabriel Popescu
Lucian Gabriel Popescu
A Simple Logging Class For PHP

KLogger: Simple Logging for PHP A project written by Kenny Katzgrau and Dan Horrigan. About KLogger is an easy-to-use PSR-3 compliant logging class fo

Kenny Katzgrau 964 Dec 11, 2022
PHP logging library that is highly extendable and simple to use.

Analog - Minimal PHP logging library Copyright: (c) 2012-Present Johnny Broadway License: MIT A minimal PHP logging package based on the idea of using

Aband*nthecar 331 Dec 21, 2022
🐣 Backend-Logging aller Aktionen im Backend

Addon BE_Logger - Backend-Logging Mit dem Addon be_logger können die Backend-Zugriffe aller Benutzer in einer Logging-Tabelle ausgegeben werden. Es gi

Friends Of REDAXO 14 Sep 12, 2022
RadPHP Logging Component

RadPHP Logging Component The Logging library provides multiple logging adapters using a simple interface. With the Logger class it is possible to send

RadPHP 9 Sep 8, 2021
Monolog logging support for Slim Framework

Monolog Logging for Slim Framework This repository adds support for logging to Monolog to the Slim Framework. Installation MonologWriter takes an arra

null 113 Dec 18, 2022
DatabaseLog CakePHP plugin to log into DB instead of files. Better to filter and search.

CakePHP DatabaseLog Plugin DatabaseLog engine for CakePHP applications. This branch is for CakePHP 4.0+. See version map for details. Features Easy se

Mark Sch. 41 Jul 29, 2022
123Solar is a set of PHP/JS files that make a web logger to monitor your photovoltaic inverter(s)

123Solar is a set of PHP/JS files that make a web logger to monitor your photovoltaic inverter(s). It just need a web server and PHP, no databases are even needed. The philosophy is: To keep it simple, fast, with a low foot print to run on cheap and low powered devices.

null 30 Jan 6, 2023
AcLog is a simple, zero-dependency PHP package to log activity to files

AcLog is a simple, zero-dependency PHP package to log activity to files. This is not meant for logging errors, this is can be used for logging c

null 2 Sep 9, 2022
Sends your logs to files, sockets, inboxes, databases and various web services

Monolog - Logging for PHP Monolog sends your logs to files, sockets, inboxes, databases and various web services. See the complete list of handlers be

Jordi Boggiano 20.1k Jan 8, 2023
Sends your logs to files, sockets, inboxes, databases and various web services

Monolog - Logging for PHP ⚠ This is the documentation for Monolog 3.x, if you are using older releases see the documentation for Monolog 2.x or Monolo

Jordi Boggiano 20.1k Jan 7, 2023