Git Product home page Git Product logo

log's Introduction

APIx Log, very thin PSR-3 logger Build Status

Latest Stable Version Total Downloads Build Status Code Quality Code Coverage License

Minimalist and fast PSR-3 compliant logger.

  • Light, come out-of-the-box bundle with wrappers for:
    • ErrorLog, File, Mail, Sapi ~ built around the error_log() function,
    • Runtime ~ as an Array/ArrayObject wrapper, and Nil ~ as Null wrapper,
    • Stream ~ logs are sent to sockets, local and remote files, filters and other similar resources (default to standard output bypassing output buffering).
  • Extendable, additional logging backends are available:
  • Clean API, see the LoggerInterface and the LogFormatterInterface.
  • 100% Unit tested and compliant with PSR0, PSR1 and PSR2.
  • Continuously integrated against 7.0, 8.x, and HHVM (use ^1.1 for older PHP versions).
  • Available as a Composer and as a PEAR package.

Feel free to comment, send pull requests and patches...

๐Ÿ†• Log dispatch can be postponed/accumulated using setDeferred().

Basic usage ~ standalone

$urgent_logger = new Apix\Log\Logger\Mail('[email protected]');
$urgent_logger->setMinLevel('critical');   // catch logs >= to `critical`

This simple logger is now set to intercept critical, alert and emergency logs.

To log an event, use:

$urgent_logger->alert('Running out of {stuff}', ['stuff' => 'beers']);

Advanced usage ~ multi-logs dispatcher

Lets create an additional logger with purpose of catching log entries that have a severity level of warning or more -- see the log levels for the order.

$app_logger = new Apix\Log\Logger\File('/var/log/apix_app.log');
$app_logger->setMinLevel('warning')  // intercept logs that are >= `warning`
           ->setCascading(false)     // don't propagate to further buckets
           ->setDeferred(true);      // postpone/accumulate logs processing

setCascading() was set to false (default is true) so the entries caught here won't continue downstream past that particular log bucket. setDeferred() was set to true (default is false) so processing happen on __destruct (end of script generally) rather than on the fly.

Now, lets create a main logger object and inject the two previous loggers.

// The main logger object (injecting an array of loggers)
$logger = new Apix\Log\Logger( array($urgent_logger, $app_logger) );

Lets create an additional logger -- just for development/debug purposes.

if(DEBUG) {
  // Bucket for the remaining logs -- i.e. `notice`, `info` and `debug`
  $dev_logger = new Apix\Log\Logger\Stream(); // default to screen without output buffer
  // $dev_logger = new Logger\File('/tmp/apix_debug.log'); 
  $dev_logger->setMinLevel('debug');

  $logger->add($dev_logger);   		// another way to inject a log bucket
}

Finally, lets push some log entries:

$e = new \Exception('Boo!');

// handled by both $urgent_logger & $app_logger
$logger->critical('OMG saw {bad-exception}', [ 'bad-exception' => $e ]);

// handled by $app_logger
$logger->error($e); // push an object (or array) directly

// handled by $dev_logger
$logger->info('Testing a var {my_var}', array('my_var' => array(...)));

Log levels

The eight RFC 5424 levels of logs are supported, in cascading order:

Severity Description
Emergency System level failure (not application level)
Alert Failure that requires immediate attention
Critical Serious failure at the application level
Error Runtime errors, used to log unhandled exceptions
Warning May indicate that an error will occur if action is not taken
Notice Events that are unusual but not error conditions
Info Normal operational messages (no action required)
Debug Verbose info useful to developers for debugging purposes (default)

Installation

Install the current major version using Composer with (recommended)

$ composer require apix/log:1.2.*

Or install the latest stable version with

$ composer require apix/log

License

APIx Log is licensed under the New BSD license -- see the LICENSE.txt for the full license details.

log's People

Contributors

8ctopus avatar frqnck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

log's Issues

Logger separators are not preserved when injected

Hi,
first of all, great logger!
When I merge two loggers with different separators the merged logger has it's own separator instead of keeping the ones I set before.

$streamFormatter = new LogFormatter();
$streamFormatter->separator = '|';

$streamLogger = new Logger\Stream('php://output');
$streamLogger->setLogFormatter($streamFormatter);
$streamLogger->info('stream');

$fileFormatter = new LogFormatter();
$fileFormatter->separator = '#';

$fileLogger = new Logger\File('logs/log_'.date('Y-m-d').'.log');
$fileLogger->setLogFormatter($fileFormatter);
$fileLogger->info('file');

$mergedLogger = new Logger(array($streamLogger, $fileLogger));
$mergedLogger->info('merged');

In this example the output in screen is:
"stream|merged
"
and in the file:
"file#merged
"
when I expected
"stream|merged|"
and
"file#merged#"

Is this a bug or a feature?
Thanks in advance

Huge speed boost compared to monolog

Hey Franck,

Did some speed tests comparing Apix vs. Monolog, it turns out in deferred mode, the speed gains are huge.

-----------------------------------
platform           :      WINNT x64
php version        :          8.1.4
xdebug             :             on
memory limit       :           512M
max execution      :              0
time per iteration :           20ms
iterations         :            250
-----------------------------------
---------------------------------------------------------------
0                  : logger_monolog   logger_apix
mean               :             25          1430      +5564.1%
median             :             18          1756      +9934.3%
mode               :              3          2013     +67000.0%
minimum            :              1            28      +2700.0%
maximum            :             73          2183      +2890.4%
quartile 1         :              5           750     +14900.0%
quartile 3         :             51          1979      +3780.4%
IQ range           :             46          1229      +2571.7%
std deviation      :             21           654      +2941.1%
normality          :          30.7%         30.7%
---------------------------------------------------------------

And respective code

$file = new Apix\Log\Logger\File('log_apix.log');
$file
    // intercept logs that are >= `warning`
    ->setMinLevel('warning')
    // don't propagate to further buckets
    ->setCascading(true)
    // postpone/accumulate logs processing
    ->setDeferred(true);

$log = new Apix\Log\Logger([$file]);

$stdout = new Apix\Log\Logger\Stream('php://stdout', 'a');
$stdout
    // intercept logs that are >= `warning`
    ->setMinLevel('warning')
    // don't propagate to further buckets
    ->setCascading(true)
    // postpone/accumulate logs processing
    ->setDeferred(true);

$log->add($stdout);

while (microtime(true) < $time_limit) {
    $log->warning('test');
    ++$iterations;
}
$log = new Monolog\Logger('test');
$log->pushHandler(new Monolog\Handler\StreamHandler('log_monolog.log', Monolog\Level::Warning));

// log to stdout
$log->pushHandler(new Monolog\Handler\StreamHandler('php://stdout', Monolog\Level::Warning));

while (microtime(true) < $time_limit) {
    $log->warning('test');
    ++$iterations;
}

Mail won't send emails

Hey =)

I was searching for PSR-3 loggers and I found yours. I would like to know if this is a WIP or ready to use. I did not try it out yet, but by reading the following code I concluded that the email class is still a WIP. Is it?

https//github.com/frqnck/apix-log/blob/master/src/Logger/Mail.php#L22

It seems that the write method is the same as the ErrorLog, so it do not actually send an email.

Cheers!

What was your use case for "deferred"?

Hi @frqnck

I intend to use this library to write logs to files in JSON format, then have Fluentd / Fluentbit tail these files for further processing.

I'd be interested in the "deferred" option to avoid writing to a file on disk all throughout script execution (seems cleaner to me to make one big write at the end).
However, the current implementation in AbstractLogger, method __destruct seems to just take all messages (strings), throw away the context, and write a single NOTICE entry in the log.

Why is that? I would have expected the deferred method to just process the backlog of log entries and write() them one by one.
Should you maybe clarify the way it works in the README?

Also, is there any technical reason for the "final" keyword on __destruct in AbstractLogger?

Thanks

Would be nice to be able to change format without subclassing

Python does this really well:
https://docs.python.org/2/library/logging.html#formatter-objects

It would be nice to be able to change the output format of the logger without having to create a subclass of the LogFormatter, which really looks like its geared to providing output that is significantly different - e.g. the Json example in the test case. But, for example, changing the default output to just the message as opposed to a date prefix doesn't seem like it should require writing a new class.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.