Skip to content

Commit

Permalink
Merge pull request #2 from kodedphp/2.0-dev
Browse files Browse the repository at this point in the history
Version 2.0
  • Loading branch information
kodeart authored Dec 10, 2019
2 parents efa8017 + 5de6099 commit d3c12f7
Show file tree
Hide file tree
Showing 35 changed files with 769 additions and 422 deletions.
11 changes: 8 additions & 3 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
*.php diff=php

/Tests export-ignore
/phpunit.* export-ignore
/*.yml export-ignore
/build export-ignore
/Tests export-ignore
/vendor export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/composer.lock export-ignore
/.dist export-ignore
/.yml export-ignore
14 changes: 7 additions & 7 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
build
vendor
.DS_Store
.idea
build/
logs/
vendor/
.DS_Store/
.idea/
composer.lock
phpunit.phar
*.yml
!.travis.yml
*.phar
*.cache
22 changes: 22 additions & 0 deletions .scrutinizer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
build:
nodes:
analysis:
tests:
stop_on_failure: true
override:
- php-scrutinizer-run
environment:
php:
version: '7.2'
dependencies:
override:
- composer install --no-interaction --prefer-source

filter:
excluded_paths:
- 'Tests/'
- 'vendor/'

tools:
php_analyzer: true
external_code_coverage: true
32 changes: 24 additions & 8 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
language: php
sudo: false

php:
- 7.2
- 7.3
- nightly

matrix:
include:
- php: 7.1
fast_finish: true
before_script:
- mkdir -p build/logs
- composer update -o --prefer-dist
allow_failures:
- php: nightly

install:
- travis_retry composer update -o --no-interaction --prefer-source

script:
- phpunit
- vendor/bin/phpunit --coverage-clover build/coverage/clover.xml

after_success:
- travis_retry php vendor/bin/coveralls
- travis_retry vendor/bin/ocular code-coverage:upload --format=php-clover build/coverage/clover.xml

sudo: false

notifications:
email: false

cache:
directories:
- $HOME/.composer/cache
19 changes: 9 additions & 10 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
BSD 3-Clause License

Koded - Logging
Copyright (c) 2018, Mihail Binev
Copyright (c) 2019, Mihail Binev
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Expand Down
160 changes: 73 additions & 87 deletions Log.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
<?php

/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <[email protected]>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*
*/

namespace Koded\Logging;

use DateTime;
use DateTimeZone;
use Koded\Logging\Processors\{ ErrorLog, Processor };
use Koded\Logging\Processors\{Cli, Processor};
use Psr\Log\LoggerTrait;
use Throwable;

Expand All @@ -16,39 +24,49 @@
*
* CONFIGURATION PARAMETERS (Log class)
*
* - deferred (bool) [optional], default: false
* A flag to set the Log instance how to dump messages.
* Set to TRUE if you want to process all accumulated messages
* at shutdown time. Otherwise, the default behavior is to process
* the message immediately after the LoggerInterface method is called.
*
* - loggers (array)
* An array of log processors. Every processor is defined in array with it's own
* configuration parameters, but ALL must have the following:
*
* - class (string) [required]
* The name of the log processor class.
* Can create multiple same instances with different config
* parameters.
* - class (string) [required]
* The name of the log processor class.
* Can create multiple same instances with different config
* parameters.
*
* - levels (integer) [optional], default: -1 (for all levels)
* Packed integer for bitwise comparison. See the constants in this
* class.
* - levels (integer) [optional], default: -1 (for all levels)
* Packed integer for bitwise comparison. See the constants in this
* class.
*
* Example: Log::INFO | Log::ERROR | Log::ALERT
* Processor with these log levels will store only
* info, error and warning type messages.
* Example: Log::INFO | Log::ERROR | Log::ALERT
* Processor with these log levels will store only
* info, error and warning type messages.
*
* - dateformat (string) [optional], default: d/m/Y H:i:s
* - dateformat (string) [optional], default: d/m/Y H:i:s.u
* The date format for the log message.
*
* - timezone (string) [optional], default: UTC
* The desired timezone for the DateTimeZone object.
*
*
* CONFIGURATION PARAMETERS (Processor class)
* Every processor has it's own specific parameters (with the above directives).
* Every processor may have it's own specific parameters.
*
*/
class Log implements Logger
{

use LoggerTrait;

/**
* @var bool Flag to control the messages processing
*/
private $deferred = false;

/**
* @var string The date format for the message.
*/
Expand Down Expand Up @@ -76,26 +94,28 @@ class Log implements Logger
*/
public function __construct(array $settings)
{
$this->dateFormat = $settings['dateformat'] ?? 'd/m/Y H:i:s';
$this->timezone = $settings['timezone'] ?? $this->timezone;
$this->deferred = (bool)($settings['deferred'] ?? false);
$this->dateFormat = (string)($settings['dateformat'] ?? 'd/m/Y H:i:s.u');
$this->timezone = (string)($settings['timezone'] ?? $this->timezone);

// Build and attach all requested processors
foreach ($settings['loggers'] ?? [] as $processor) {
foreach ((array)($settings['loggers'] ?? []) as $processor) {
$this->attach(new $processor['class']($processor));
}

if ($this->deferred) {
register_shutdown_function([$this, 'process']);
}
}

/**
* {@inheritdoc}
*/
public function register()
public function attach(Processor $processor): Logger
{
register_shutdown_function([$this, 'process']);
if (0 !== $processor->levels()) {
$this->processors[spl_object_hash($processor)] = $processor;
}

return $this;
}

/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = [])
{
try {
Expand All @@ -106,38 +126,35 @@ public function log($level, $message, array $context = [])
$level = -1;
}

$microtime = microtime(true);

$this->messages[] = [
'level' => $level,
'level' => $level,
'levelname' => $levelname,
'message' => $this->formatMessage($message, $context),
'timestamp' => (
(new DateTime(null, new DateTimeZone('UTC')))
->setTimestamp($microtime)
->format($this->dateFormat)
) . substr(sprintf('%.6F', $microtime), -7)
'message' => $this->formatMessage($message, $context),
'timestamp' => date_create_immutable('now', timezone_open($this->timezone))->format($this->dateFormat),
];

$this->deferred || $this->process();
}

/**
* {@inheritdoc}
* Parses the message as in the interface specification.
*
* @param string|object $message A string or object that implements __toString
* @param array $params [optional] Arbitrary data with key-value pairs replacements
*
* @return string
*/
public function exception(Throwable $e, Processor $processor = null)
private function formatMessage($message, array $params = []): string
{
$syslog = $processor ?? new ErrorLog([]);
$message = $e->getMessage() . PHP_EOL . ' -- [Trace]: ' . $e->getTraceAsString();
$replacements = [];
foreach ($params as $k => $v) {
$replacements['{' . $k . '}'] = $v;
}

$this->attach($syslog);
$this->alert($message);
$this->process();
$this->detach($syslog);
return strtr((string)$message, $replacements);
}

/**
* {@inheritdoc}
*/
public function process()
public function process(): void
{
foreach ($this->processors as $processor) {
$processor->update($this->messages);
Expand All @@ -146,51 +163,20 @@ public function process()
$this->messages = [];
}

/**
* Add a log processor in the stack.
*
* @param Processor $processor Logger processor instance
*
* @return Log
*/
public function attach(Processor $processor): Log
public function exception(Throwable $e, Processor $processor = null): void
{
if (0 !== $processor->levels()) {
$this->processors[spl_object_hash($processor)] = $processor;
}
$logger = $processor ?? new Cli([]);
$message = $e->getMessage() . PHP_EOL . ' -- [Trace]: ' . $e->getTraceAsString();

return $this;
$this->attach($logger)->critical($message);
$this->process();
$this->detach($logger);
}

/**
* Detach a log processor from registered processors.
*
* @param Processor $processor The log processor to detach from the stack.
*
* @return Log
*/
public function detach(Processor $processor): Log
public function detach(Processor $processor): Logger
{
unset($this->processors[spl_object_hash($processor)]);

return $this;
}

/**
* Parses the message as in the interface specification.
*
* @param string|object $message A string or object that implements __toString
* @param array $context [optional] Arbitrary data with key-value pairs replacements
*
* @return string
*/
private function formatMessage($message, array $context = []): string
{
$replacements = [];
foreach ($context as $k => $v) {
$replacements['{' . $k . '}'] = $v;
}

return strtr((string)$message, $replacements);
}
}
Loading

0 comments on commit d3c12f7

Please sign in to comment.