PHP Classes

ITE Logger: Log messages to different storage PSR-3 compliant

Recommend this page to a friend!
  Info   View files Example   View files View files (147)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 152 All time: 9,014 This week: 246Up
Version License PHP version Categories
ite-logger 1.2.3BSD License5.6PHP 5, Logging, Stream wrappers, Traits, P...
Description 

Author

This package can log messages to different storage containers compliant with PSR-3.

It provides classes to log messages to files and abstract classes for sending emails with logs and writing them to database.

It also has classes using the php function mail() for sending logs and PDO for storing log messages to database tables.

This package includes a LoggerAggregator class and trait that allows using of multiple nested loggers for all or different log levels.

It also provides a stream namespace with a trait, classes and interfaces that can be useful to write logs with stream functions, like fopen('log://<logger-type>/<log-level>', 'w').

Recommendations

Create a logger to an application
I need a logger class to insert in file or database.

Innovation Award
PHP Programming Innovation award nominee
September 2016
Number 7


Prize: One ebook of choice by Packt
PSR-3 is a standards recommendation that defines a common interface to implement logger classes.

This package implements the PSR-3 logger interface using several types of classes, as well a class and a trait that allows using multiple nested loggers.

It also provides a stream wrapper that allows developers to write to logs using regular file access functions.

Manuel Lemos
Picture of Kiril Savchev
  Performance   Level  
Innovation award
Innovation award
Nominee: 5x

 

Details

If-Then-Else Logger package

Description

Set of classes the can be used for logging messages.

It provides simple file logging and abstract classes for sending emails with logs and writing them to database. It also has simple classes using internal php function mail() for sending logs and \PDO for writing into database tables. This packages includes LoggerAggregator class and trait that allow using of multiple nested loggers for all or different levels.

All the loggers implements PSR-3 logger standards. See http://www.php-fig.org/psr/psr-3/ for more information.

Usage

First run 'composer install' to install psr/log package. You can see the following examples in the 'example' folder

FileLogger example:

<?php

require_once '../vendor/autoload.php';

// Create the file logger with concrete log fils for 'alert' and 'error' levels:
$logger = new \Ite\Logger\FileLogger([
        'error' => '../data/logs/errors.log',
        'alert' => '../data/logs/errors.log'
]);
// the rest of levels will use the default log file

// log 10 info messages with fake context:
for ($i=0; $i<10; $i++) {
        $logger->info("Test info {$i}",['a' => 'test context', 'qwe' => 'alabala', 'q' => [1, 2, 4]]);
}
// log 10 error messages with exception:
for ($i=0; $i<10; $i++) {
        $logger->error("Test error {$i}", ['exception' => new Exception("Tesitng exceptions")]);
}
// log 10 alert messages with exception and fake context:
for ($i=0; $i<10; $i++) {
        $logger->alert("Test alert {$i}", ['exception' => new Exception("Tesitng exceptions"), 'a' => 'test context', 'qwe' => 'alabala', 'q' => [1, 2, 4]]);
}

PhpMailLogger example:

<?php

require_once '../vendor/autoload.php';

use Ite\Logger\PhpMailLogger;

// Change the email addres to yours:
$logger = new PhpMailLogger('me@xample.com');

// Log simple info message with fake content:
$logger->info("Test info",['a' => 'test context', 'nested_context' => [1, 2, 4]]);

PdoMysqlLogger example:

<?php

require_once '../vendor/autoload.php';

$dbConfig = [
        'host' => 'localhost',
        'name' => '{{DATABASE_NAME}}', // set your own here
        'username' => '{{USERNAME}}', // set your own here
        'password' => '{{PASSWORD}}', // set your own here
        'options' => [
                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"
        ]
];

/*
 *
 * You need to execute this query to use this logger:

CREATE TABLE logs(
        id INT(11) NOT NULL AUTO_INCREMENT,
        message VARCHAR(255) NOT NULL,
        level VARCHAR(10) NOT NULL,
        date DATETIME NOT NULL,
        context TEXT,
        PRIMARY KEY(ID)
);

*/

$logger = new Ite\Logger\PdoMysqlLogger($dbConfig);
$logger->info("Testing database", ['key1' => 'value1']);
$logger->alert("Testing database", ['alert' => 'alerting']);

LoggerAggregator example:

<?php

require_once '../vendor/autoload.php';

use Ite\Logger\FileLogger;
use Ite\Logger\LoggerAggregator;
use Ite\Logger\PhpMailLogger;

// create some simple loggers:
$logger = new FileLogger(['error' => '../data/logs/errors.log', 'alert' => '../data/logs/errors.log']);
$logger2 = new FileLogger();
$logger3 = new FileLogger();
$logger3->setDefaultLog('../data/logs/all.log');
// Change the email addres to yours:
$emailLogger = new PhpMailLogger('me@xample.com');

// create Logger Aggregator with a nested logger for 'error' and 'alert' level:
$loggerAggregator = new LoggerAggregator(['error' => $logger, 'alert' => $logger]);
// attach logger for 'info', 'debug' and 'error' levels:
$loggerAggregator->attachLogger($logger2, ['info', 'debug', 'error']);
// attach logger for all log levels:
$loggerAggregator->attachLogger($logger3);
// remove a logger for 'debug' level:
$loggerAggregator->detachLogger($logger2, 'debug');
// add email logger for critical messages:
$loggerAggregator->attachLogger($emailLogger, 'critical');

// fire some loggings:
for ($i=0; $i<10; $i++) {
        $loggerAggregator->info("Test info {$i}",['a' => 'test context', 'qwe' => 'alabala']);
}
for ($i=0; $i<10; $i++) {
        $loggerAggregator->error("Test error {$i}", ['exception' => new Exception("Tesitng exceptions")]);
}
for ($i=0; $i<10; $i++) {
        $loggerAggregator->alert("Test alert {$i}", ['exception' => new Exception("Tesitng exceptions"),'a' => 'test context', 'qwe' => 'alabala']);
}
for ($i=0; $i<10; $i++) {
        $loggerAggregator->debug("Test debug {$i}");
}
// Fire criticial log message (this should send email):
$loggerAggregator->critical("Critical message");

Stream logging:

<?php

require_once '../vendor/autoload.php';

use Ite\Logger\Stream\Strategy\AbstractDatabaseLoggerStrategy;
use Ite\Logger\Stream\Strategy\AbstractEmailLoggerStrategy;
use Ite\Logger\Stream\StreamLoggerTrait;
use Ite\Logger\Stream\FileLogger;
use Ite\Logger\Stream\PhpMailLogger;
use Ite\Logger\Stream\PdoMysqlLogger;
use Psr\Log\LoggerInterface;

# Test database logger:
//stream_register_wrapper('log', PdoMysqlLogger::class);
//$stream = fopen('log://db/info', 'w');

# Test email logger:
//stream_register_wrapper('log', PhpMailLogger::class);
//$stream = fopen('log://email/info?to=k.savchev@gmail.com', 'w');

# Test file logger:
stream_register_wrapper('log', FileLogger::class);
$stream = fopen('log://file/info?log=../data/logs/errors.log', 'w', STREAM_REPORT_ERRORS);

// Write log:
fwrite($stream, serialize(["Testing stream...", [1, 2, 3]]));
  Files folder image Files  
File Role Description
Files folder imagedata (1 directory)
Files folder imagedocs (2 files, 9 directories)
Files folder imageexamples (5 files)
Files folder imagesrc (10 files, 2 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file composer.lock Data Auxiliary data
Accessible without login Plain text file license Lic. License text
Accessible without login Plain text file README.md Data Auxiliary data

 Version Control Unique User Downloads Download Rankings  
 100%
Total:152
This week:0
All time:9,014
This week:246Up