PHP logging library that is highly extendable and simple to use.

Overview

Analog - Minimal PHP logging library

  • Copyright: (c) 2012-Present Johnny Broadway
  • License: MIT

A minimal PHP logging package based on the idea of using closures for configurability and extensibility. It functions as a static class, but you can completely control the writing of log messages through a closure function (aka anonymous functions), or use the Analog\Logger wrapper that implements the PSR-3 specification.

Installation

Install the latest version with:

$ composer require analog/analog

Usage

Basic Usage

<?php

use Analog\Analog;
use Analog\Handler\FirePHP;

Analog::handler (FirePHP::init ());

Analog::log ('Take me to your browser');

Usage with PSR-3

<?php

use Analog\Logger;
use Analog\Handler\Variable;

$logger = new Logger;

$log = '';

$logger->handler (Variable::init ($log));

$logger->alert ('Things are really happening right now!');

var_dump ($log);

Usage with a custom handler

<?php

use Analog\Analog;

// Default logging to /tmp/analog.txt
Analog::log ('Log this error');

// Log to a MongoDB log collection
Analog::handler (function ($info) {
	static $conn = null;
	if (! $conn) {
		$conn = new Mongo ('localhost:27017');
	}
	$conn->mydb->log->insert ($info);
});

// Log an alert
Analog::log ('The sky is falling!', Analog::ALERT);

// Log some debug info
Analog::log ('Debugging info', Analog::DEBUG);

Usage without composer

Analog uses a simple autoloader internally, so if you don't have access to composer you can clone this repository and include it like this:

<?php

require 'analog/lib/Analog.php';

Analog::handler (Analog\Handler\Stderr::init ());

Analog::log ('Output to php://stderr');

For more examples, see the examples folder.

Logging Options

By default, this class will write to a file named sys_get_temp_dir() . '/analog.txt' using the format "machine - date - level - message\n", making it usable with no customization necessary.

Analog also comes with dozens of pre-written handlers in the Analog/Handlers folder, with examples for each in the examples folder. These include:

  • Amon - Send logs to the Amon server monitoring tool
  • Apprise - Send notifications through the apprise command line tool
  • Buffer - Buffer messages to send all at once (works with File, Mail, Stderr, and Variable handlers)
  • ChromeLogger - Sends messages to Chrome Logger browser plugin
  • EchoConsole - Echo output directly to the console
  • File - Append messages to a file
  • FirePHP - Send messages to FirePHP browser plugin
  • GELF - Send message to the Graylog2 log management server
  • IFTTT - Trigger webhooks via the IFTTT service
  • Ignore - Do nothing
  • LevelBuffer - Buffer messages and send only if sufficient error level reached
  • LevelName - Convert log level numbers to names in log output
  • Mail - Send email notices
  • Mongo - Save to MongoDB collection
  • Multi - Send different log levels to different handlers
  • PDO - Send messages to any PDO database connection (MySQL, SQLite, PostgreSQL, etc.)
  • Post - Send messages over HTTP POST to another machine
  • Redis - Save messages to Redis key using RPUSH
  • Slackbot - Post messages to Slack via Slackbot
  • Stderr - Send messages to STDERR
  • Syslog - Send messages to syslog
  • Threshold - Only writes log messages above a certain threshold
  • Variable - Buffer messages to a variable reference
  • WPMail - Send email notices using Wordpress wp_mail()

So while it's a micro class, it's highly extensible and very capable out of the box too.

Rationale

I wrote this because I wanted something very small and simple like KLogger, and preferably not torn out of a wider framework if possible. After searching, I wasn't happy with the single-purpose libraries I found. With KLogger for example, I didn't want an object instance but rather a static class, and I wanted more flexibility in the back-end.

I also found some that had the flexibility also had more complexity, for example Monolog is dozens of source files (not incl. tests). With closures, this seemed to be a good balance of small without sacrificing flexibility.

What about Analog, the logfile analyzer? Well, since it hasn't been updated since 2004, I think it's safe to call a single-file PHP logging class the same thing without it being considered stepping on toes :)

Comments
  • Fix per-level functions to not throw undefined constant warnings

    Fix per-level functions to not throw undefined constant warnings

    The class constants need to be prefixed with self:: (or the class name, but self:: makes it always do the right thing if Analog gets subclassed), otherwise PHP doesn't recognize DEBUG et. al. as class constants and throws a fit.

    opened by lord2800 5
  • Could not lock file

    Could not lock file

    Hello, I'm sometimes throwing the following error: exception 'RuntimeException' with message 'Could not lock file' in /home/travis/build/galette/galette/galette/includes/Analog-1.0.0.git876d8a3bb/Analog/Handler/File.php:27

    That file should not be locked, it is used by Analog only.

    I do not know how to reproduce it, I had it a very few times using my application; but that regulary fail on my travis unit tests.

    Of course, I could disable file logging during tests to avoid that; but I'm afraid my users may throw the same issue on some configurations.

    Any idea how to fix that?

    opened by trasher 5
  • Mix Multi and Threshold handlers

    Mix Multi and Threshold handlers

    Hello,

    Using Mutli or Threshold handler separately works fine; but I can't achieve to get them working together. I'm using files to log, and I'd like to get two separate files:

    • one for notices, warnings, errors, etc
    • another for info and debug messages (because those ones may be very verbose).

    Giving the the following example:

    $errors = "Errors:\n";
    $debug = "Debug:\n";
    
    \Analog\Analog::handler(
        \Analog\Handler\Multi::init(
            array (
                \Analog\Analog::NOTICE  => \Analog\Handler\Threshold::init(
                    \Analog\Handler\Variable::init($errors),
                    \Analog\Analog::NOTICE
                ),
                Analog::DEBUG       => \Analog\Handler\Threshold::init(
                    \Analog\Handler\Variable::init($debug),
                    \Analog\Analog::DEBUG
                )
            )
        )
    );
    
    \Analog\Analog::log(
        'An error',
        \Analog\Analog::ERROR
    );
    
    
    \Analog\Analog::log(
        'A debug message',
        \Analog\Analog::DEBUG
    );
    
    var_dump($errors);
    var_dump($debug);
    

    The output is:

    string 'Errors:
    ' (length=8)
    
    string 'Debug:
    127.0.0.1 - 2016-11-16 21:32:13 - 3 - An error
    127.0.0.1 - 2016-11-16 21:32:13 - 7 - A debug message
    ' (length=108)
    
    

    But what I was expecting was "An error" to be written in $errors, and "A debug message" to $debug.

    Did I miss something?

    Thank you very much!

    opened by trasher 3
  • Output converted log level

    Output converted log level

    https://github.com/jbroadway/analog/blob/32ccdc89082a1cf9e471f4ce69f1c05bf741b34e/lib/Analog/Logger.php#L212

    According to this comment, the logging level seems to be output after being converted, but the actual output is a number. Is this a bug?

    opened by Nerahikada 2
  • Composer can't find analog

    Composer can't find analog

    Hi there,

    I seem to be unable to install analog on my server. I have several other libraries installed via composer (Stripe, PayPal, Google API, Medoo, etc. but can't seem to find yours. I've included the console log:

    -bash-4.2$ composer require jbroadway/analog
      [InvalidArgumentException]
      Could not find a matching version of package jbroadway/analog. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (stable).
    require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--update-with-all-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...
    
    opened by Invincibear 2
  • Cannot use 'Null' as class name as it is reserved

    Cannot use 'Null' as class name as it is reserved

    https://github.com/jbroadway/analog/blob/08ec5a01769fbebeb13df4900ecdd48914b1dc42/lib/Analog/Handler/Null.php#L17

    phpstan says: Cannot use 'Null' as class name as it is reserved - and i guess, it´s right 😏

    opened by michabbb 2
  • Class Mail. Request best config

    Class Mail. Request best config

    Hi.

    On this days it's best way to send email trought authenticate SMTP )spam system, security) It's possible add funcionality on nexts versions?

    Apreciate you time.

    opened by abkrim 2
  • Add Handler for sending emails from WordPress

    Add Handler for sending emails from WordPress

    Add custom handler to send HTML email from WordPress. It uses the WP native wp_mail function and allows you to have a template in your theme with some design for the log email.

    opened by MZAWeb 2
  • Please tag releases (e.g. major.minor.patch)

    Please tag releases (e.g. major.minor.patch)

    Hi there =)

    Would love it if you can tag releases, including patch updates, so that they are usable through Composer. As it stands, Analog's composer.json points to dev-master, which means it is automatically "dev" stability.

    If a second library requires Analog, the end-user has to either specify 'dev' stability for all packages (not good), or specifically include Analog. Stability is not inherited (e.g. Library B which requires Analog cannot specify the stability), and so things break because everything is just thrown into dev-master.

    Ultimately, this leads to composer files like this (where other/library requires Analog):

    {
        "require": {
            "other/library" : "0.1.*",
            "analog/analog": "dev-master"
        }
    }
    

    When really it should just be:

    {
        "require": {
            "other/library" : "0.1.*"
        }
    }
    
    opened by polyfractal 2
  • Maximum execution time exceeded (not really a bug)

    Maximum execution time exceeded (not really a bug)

    That is not really an issue, I made a mistake in my code, causing Analog to excess maximum execution time; using multi handler.

    My stuff is wrong, not Analog one; but it was quite difficult to figure out what was happening :-)

    I get something like:

    Analog::log(
        'My message',
        OLD_CONSTANT
    );
    

    The "OLD_CONSTANT" value is the issue, since it no longer exists, PHP use constant name as a text value. Once in Analog/Handler/Multi.php file, we go through the while instruction that never ends because of the string instead of integer.

    Maybe it would be useful to check if $info['level'] is an integer before entering the while, and either throw an exception or take a default arbitrary value.

    opened by trasher 2
  • Uncaught Error: Undefined class constant 'ATTR_ERRMODE' in  analog/analog/lib/Analog/Handler/PDO.php:52

    Uncaught Error: Undefined class constant 'ATTR_ERRMODE' in analog/analog/lib/Analog/Handler/PDO.php:52

    Uncaught Error: Undefined class constant 'ATTR_ERRMODE' in ..../vendor/analog/analog/lib/Analog/Handler/PDO.php:52

    Because your class named PDO(as global) but your had no CONST NAMES!!!!! set \PDO const names instead PDO you forgot a slash sign, like:

    class PDO {
    	public static function init ($pdo, $table) {
    		if (is_array ($pdo)) {
    			$pdo = new \PDO ($pdo[0], $pdo[1], $pdo[2], [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
    		}
    

    cause if i send $pdo as PDO object, it all works well, untill i send as array, and all executed as (without slash)

    class PDO {
    	public static function init ($pdo, $table) {
    		if (is_array ($pdo)) {
    			$pdo = new \PDO ($pdo[0], $pdo[1], $pdo[2], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    		}
    
    opened by v0ff4k 1
Releases(1.0.19-stable)
Owner
Aband*nthecar
Full-stack developer. One-man synthpop band. CTO/Co-Founder @ HeyAlfa + Flipside XR.
Aband*nthecar
High-performance API performing logging for PHP applications into files or SysLog

Logging API Table of contents: About Configuration Binding Points Logging Installation Unit Tests Reference Guide Specifications How Are Log Lines For

Lucian Gabriel Popescu 0 Jan 9, 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
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

Remon 4 Apr 26, 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
Slim-Logger - A stand-alone logger class for use with the Slim Framework

Slim-Logger - A stand-alone logger class for use with the Slim Framework

Josh Lockhart 41 Mar 12, 2022
ChromePhp - a PHP library for the Chrome Logger Google Chrome extension

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

Craig Campbell 1.4k Dec 30, 2022
A simple and beautiful laravel log reader

Laravel Log Reader A simple and beautiful laravel log reader Documentation Get full documentation of Laravel Log Reader Other Packages Laravel H - A h

Md.Harun-Ur-Rashid 356 Dec 30, 2022
Simple PHP Logger. Composer package

Basic PHP Logger ?? Simple logger. Composer package.

null 1 Jan 28, 2022
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
Amazon Web Services CloudWatch Logs Handler for Monolog library

AWS CloudWatch Logs Handler for Monolog Handler for PHP logging library Monolog for sending log entries to AWS CloudWatch Logs service. Before using t

Maksym Leonov 377 Dec 16, 2022
A simple database logger for all outgoing emails sent by Laravel website.

Laravel Email Database Log A simple database logger for all outgoing emails sent by Laravel website.

Shvets Group 136 Jan 4, 2023
temperature-pi: a simple Raspberry Pi based temperature logger using a DS18B20 1-Wire digital temperature sensor, & a local sqlite database

temperature-pi temperature-pi is a simple Raspberry Pi based temperature logger using a DS18B20 1-Wire digital temperature sensor, & a local sqlite da

Ronan Guilloux 23 Dec 27, 2020
Capture and monitor detailed error logs with nice dashboard and UI

Capture and monitor detailed error logs with nice dashboard and UI Requirements Check Laravel 6 requirements Check Laravel 7 requirements Installation

Bugphix 107 Dec 12, 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
Flexible and rock solid audit log tracking for CakePHP 3

AuditStash Plugin For CakePHP This plugin implements an "audit trail" for any of your Table classes in your application, that is, the ability of recor

José Lorenzo Rodríguez 68 Dec 15, 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
Paste, share and analyse Minecraft server logs

mclo.gs Paste, share & analyse your Minecraft server logs About The project mclo.gs was created in 2017 by the Aternos team after more than 4 years of

Aternos 99 Jan 3, 2023
Keep your laravel logs small and tidy.

Logs can get quite out of hand. This package helps save server space and keep your Laravel log files small.

Accent Interactive 73 Nov 14, 2022