Add Monolog

This commit is contained in:
Philipp Holzer 2018-12-30 21:42:56 +01:00 committed by Hypolite Petovan
parent 518f28a7bf
commit 2e602afd3e
18 changed files with 736 additions and 164 deletions

View file

@ -8,8 +8,10 @@ use Detection\MobileDetect;
use DOMDocument;
use DOMXPath;
use Exception;
use Friendica\Core\Logger;
use Friendica\Database\DBA;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Psr\Log\LoggerInterface;
/**
*
@ -106,6 +108,11 @@ class App
*/
public $mobileDetect;
/**
* @var LoggerInterface The current logger of this App
*/
private $logger;
/**
* Register a stylesheet file path to be included in the <head> tag of every page.
* Inclusion is done in App->initHead().
@ -146,13 +153,16 @@ class App
/**
* @brief App constructor.
*
* @param string $basePath Path to the app base folder
* @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
* @param string $basePath Path to the app base folder
* @param LoggerInterface $logger Logger of this application
* @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
*
* @throws Exception if the Basepath is not usable
*/
public function __construct($basePath, $isBackend = true)
public function __construct($basePath, LoggerInterface $logger, $isBackend = true)
{
$this->logger = $logger;
if (!static::isDirectoryUsable($basePath, false)) {
throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
}
@ -301,6 +311,21 @@ class App
return $this->mode;
}
/**
* Returns the Logger of the Application
*
* @return LoggerInterface The Logger
* @throws InternalServerErrorException when the logger isn't created
*/
public function getLogger()
{
if (empty($this->logger)) {
throw new InternalServerErrorException('Logger of the Application is not defined');
}
return $this->logger;
}
/**
* Reloads the whole app instance
*/
@ -328,6 +353,8 @@ class App
Core\L10n::init();
$this->process_id = Core\System::processID('log');
Core\Logger::setLogger($this->logger);
}
/**

View file

@ -6,6 +6,8 @@ namespace Friendica;
require_once 'boot.php';
use Friendica\Util\LoggerFactory;
/**
* Basic object
*
@ -25,7 +27,8 @@ class BaseObject
public static function getApp()
{
if (empty(self::$app)) {
self::$app = new App(dirname(__DIR__));
$logger = $logger = LoggerFactory::create('app');
self::$app = new App(dirname(__DIR__), $logger);
}
return self::$app;

View file

@ -4,9 +4,7 @@
*/
namespace Friendica\Core;
use Friendica\App;
use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Database\DBA;
/**
@ -76,7 +74,7 @@ class Addon extends BaseObject
*/
public static function uninstall($addon)
{
Logger::log("Addons: uninstalling " . $addon);
Logger::notice("Addon {addon}: {action}", ['action' => 'uninstall', 'addon' => $addon]);
DBA::delete('addon', ['name' => $addon]);
@include_once('addon/' . $addon . '/' . $addon . '.php');
@ -101,7 +99,7 @@ class Addon extends BaseObject
if (!file_exists('addon/' . $addon . '/' . $addon . '.php')) {
return false;
}
Logger::log("Addons: installing " . $addon);
Logger::notice("Addon {addon}: {action}", ['action' => 'install', 'addon' => $addon]);
$t = @filemtime('addon/' . $addon . '/' . $addon . '.php');
@include_once('addon/' . $addon . '/' . $addon . '.php');
if (function_exists($addon . '_install')) {
@ -126,7 +124,7 @@ class Addon extends BaseObject
}
return true;
} else {
Logger::log("Addons: FAILED installing " . $addon);
Logger::error("Addon {addon}: {action} failed", ['action' => 'uninstall', 'addon' => $addon]);
return false;
}
}
@ -156,7 +154,8 @@ class Addon extends BaseObject
$t = @filemtime($fname);
foreach ($installed as $i) {
if (($i['name'] == $addon) && ($i['timestamp'] != $t)) {
Logger::log('Reloading addon: ' . $i['name']);
Logger::notice("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $i['name']]);
@include_once($fname);
if (function_exists($addon . '_uninstall')) {

View file

@ -5,82 +5,335 @@
namespace Friendica\Core;
use Friendica\BaseObject;
use Friendica\Core\Config;
use Friendica\Util\DateTimeFormat;
use ReflectionClass;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\LoggerFactory;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* @brief Logger functions
*/
class Logger extends BaseObject
{
// Log levels:
const WARNING = 0;
const INFO = 1;
const TRACE = 2;
const DEBUG = 3;
const DATA = 4;
const ALL = 5;
/**
* @see Logger::error()
*/
const WARNING = LogLevel::ERROR;
/**
* @see Logger::warning()
*/
const INFO = LogLevel::WARNING;
/**
* @see Logger::notice()
*/
const TRACE = LogLevel::NOTICE;
/**
* @see Logger::info()
*/
const DEBUG = LogLevel::INFO;
/**
* @see Logger::debug()
*/
const DATA = LogLevel::DEBUG;
/**
* @see Logger::debug()
*/
const ALL = LogLevel::DEBUG;
public static $levels = [
self::WARNING => 'Warning',
self::INFO => 'Info',
self::TRACE => 'Trace',
self::DEBUG => 'Debug',
self::DATA => 'Data',
self::ALL => 'All',
];
/**
* @var array the legacy loglevels
* @deprecated 2019.03 use PSR-3 loglevels
* @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#5-psrlogloglevel
*
*/
public static $levels = [
self::WARNING => 'Warning',
self::INFO => 'Info',
self::TRACE => 'Trace',
self::DEBUG => 'Debug',
self::DATA => 'Data',
self::ALL => 'All',
];
/**
* @var LoggerInterface A PSR-3 compliant logger instance
*/
private static $logger;
/**
* @var LoggerInterface A PSR-3 compliant logger instance for developing only
*/
private static $devLogger;
/**
* Sets the default logging handler for Friendica.
* @todo Can be combined with other handlers too if necessary, could be configurable.
*
* @param LoggerInterface $logger The Logger instance of this Application
*
* @throws InternalServerErrorException if the logger factory is incompatible to this logger
*/
public static function setLogger($logger)
{
$debugging = Config::get('system', 'debugging');
$logfile = Config::get('system', 'logfile');
$loglevel = Config::get('system', 'loglevel');
if (!$debugging || !$logfile) {
return;
}
if (is_int($loglevel)) {
$loglevel = self::mapLegacyConfigDebugLevel($loglevel);
}
LoggerFactory::addStreamHandler($logger, $logfile, $loglevel);
self::$logger = $logger;
$logfile = Config::get('system', 'dlogfile');
if (!$logfile) {
return;
}
$developIp = Config::get('system', 'dlogip');
self::$devLogger = LoggerFactory::createDev('develop', $developIp);
LoggerFactory::addStreamHandler(self::$devLogger, $logfile, LogLevel::DEBUG);
}
/**
* Mapping a legacy level to the PSR-3 compliant levels
* @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#5-psrlogloglevel
*
* @param int $level the level to be mapped
*
* @return string the PSR-3 compliant level
*/
private static function mapLegacyConfigDebugLevel($level)
{
switch ($level) {
// legacy WARNING
case 0:
return LogLevel::ERROR;
// legacy INFO
case 1:
return LogLevel::WARNING;
// legacy TRACE
case 2:
return LogLevel::NOTICE;
// legacy DEBUG
case 3:
return LogLevel::INFO;
// legacy DATA
case 4:
return LogLevel::DEBUG;
// legacy ALL
case 5:
return LogLevel::DEBUG;
// default if nothing set
default:
return LogLevel::NOTICE;
}
}
/**
* System is unusable.
* @see LoggerInterface::emergency()
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function emergency($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->emergency($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Action must be taken immediately.
* @see LoggerInterface::alert()
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function alert($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->alert($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Critical conditions.
* @see LoggerInterface::critical()
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function critical($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->critical($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
* @see LoggerInterface::error()
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function error($message, $context = [])
{
if (!isset(self::$logger)) {
echo "not set!?\n";
return;
}
$stamp1 = microtime(true);
self::$logger->error($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Exceptional occurrences that are not errors.
* @see LoggerInterface::warning()
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function warning($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->warning($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Normal but significant events.
* @see LoggerInterface::notice()
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function notice($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->notice($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Interesting events.
* @see LoggerInterface::info()
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*
*/
public static function info($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->info($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* Detailed debug information.
* @see LoggerInterface::debug()
*
* @param string $message
* @param array $context
*
* @return void
*/
public static function debug($message, $context = [])
{
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
self::$logger->debug($message, $context);
self::getApp()->saveTimestamp($stamp1, 'file');
}
/**
* @brief Logs the given message at the given log level
*
* @param string $msg
* @param int $level
*
* @deprecated since 2019.03 Use Logger::debug() Logger::info() , ... instead
*/
public static function log($msg, $level = self::INFO)
public static function log($msg, $level = LogLevel::NOTICE)
{
$a = self::getApp();
$debugging = Config::get('system', 'debugging');
$logfile = Config::get('system', 'logfile');
$loglevel = intval(Config::get('system', 'loglevel'));
if (
!$debugging
|| !$logfile
|| $level > $loglevel
) {
return;
}
$processId = session_id();
if ($processId == '')
{
$processId = $a->process_id;
}
$callers = debug_backtrace();
if (count($callers) > 1) {
$function = $callers[1]['function'];
} else {
$function = '';
}
$logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
DateTimeFormat::utcNow(DateTimeFormat::ATOM),
$processId,
self::$levels[$level],
basename($callers[0]['file']),
$callers[0]['line'],
$function,
$msg
);
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
@file_put_contents($logfile, $logline, FILE_APPEND);
$a->saveTimestamp($stamp1, "file");
self::$logger->log($level, $msg);
self::getApp()->saveTimestamp($stamp1, "file");
}
/**
@ -90,47 +343,16 @@ class Logger extends BaseObject
* personally without background noise
*
* @param string $msg
* @param string $level
*/
public static function devLog($msg)
public static function devLog($msg, $level = LogLevel::DEBUG)
{
$a = self::getApp();
$logfile = Config::get('system', 'dlogfile');
if (!$logfile) {
return;
}
$dlogip = Config::get('system', 'dlogip');
if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip)
{
return;
}
$processId = session_id();
if ($processId == '')
{
$processId = $a->process_id;
}
if (!is_string($msg)) {
$msg = var_export($msg, true);
}
$callers = debug_backtrace();
$logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
DateTimeFormat::utcNow(),
$processId,
basename($callers[0]['file']),
$callers[0]['line'],
$callers[1]['function'],
$msg
);
if (!isset(self::$logger)) {
return;
}
$stamp1 = microtime(true);
@file_put_contents($logfile, $logline, FILE_APPEND);
$a->saveTimestamp($stamp1, "file");
self::$devLogger->log($level, $msg);
self::getApp()->saveTimestamp($stamp1, "file");
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Friendica\Util\Logger;
use Monolog\Handler;
use Monolog\Logger;
/**
* Simple handler for Friendica developers to use for deeper logging
*
* If you want to debug only interactions from your IP or the IP of a remote server for federation debug,
* you'll use Logger::develop() for the duration of your work, and you clean it up when you're done before submitting your PR.
*/
class FriendicaDevelopHandler extends Handler\AbstractHandler
{
/**
* @var string The IP of the developer who wants to debug
*/
private $developerIp;
/**
* @param string $developerIp The IP of the developer who wants to debug
* @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($developerIp, $level = Logger::DEBUG, $bubble = true)
{
parent::__construct($level, $bubble);
$this->developerIp = $developerIp;
}
/**
* {@inheritdoc}
*/
public function handle(array $record)
{
if (!$this->isHandling($record)) {
return false;
}
/// Just in case the remote IP is the same as the developer IP log the output
if (!is_null($this->developerIp) && $_SERVER['REMOTE_ADDR'] != $this->developerIp)
{
return false;
}
return false === $this->bubble;
}
}

116
src/Util/LoggerFactory.php Normal file
View file

@ -0,0 +1,116 @@
<?php
namespace Friendica\Util;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\Logger\FriendicaDevelopHandler;
use Monolog;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* A logger factory
*
* Currently only Monolog is supported
*/
class LoggerFactory
{
/**
* Creates a new PSR-3 compliant logger instances
*
* @param string $channel The channel of the logger instance
*
* @return LoggerInterface The PSR-3 compliant logger instance
*/
public static function create($channel)
{
$logger = new Monolog\Logger($channel);
$logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
$logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
// Add more information in case of a warning and more
$logger->pushProcessor(new Monolog\Processor\IntrospectionProcessor(LogLevel::WARNING, [], 1));
return $logger;
}
/**
* Creates a new PSR-3 compliant develop logger
*
* If you want to debug only interactions from your IP or the IP of a remote server for federation debug,
* you'll use this logger instance for the duration of your work.
*
* It should never get filled during normal usage of Friendica
*
* @param string $channel The channel of the logger instance
* @param string $developerIp The IP of the developer who wants to use the logger
*
* @return LoggerInterface The PSR-3 compliant logger instance
*/
public static function createDev($channel, $developerIp)
{
$logger = new Monolog\Logger($channel);
$logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
$logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
$logger->pushProcessor(new Monolog\Processor\IntrospectionProcessor(Loglevel::DEBUG, [], 1));
$logger->pushHandler(new FriendicaDevelopHandler($developerIp));
return $logger;
}
/**
* Adding a handler to a given logger instance
*
* @param LoggerInterface $logger The logger instance
* @param mixed $stream The stream which handles the logger output
* @param string $level The level, for which this handler at least should handle logging
*
* @return void
*
* @throws InternalServerErrorException if the logger is incompatible to the logger factory
* @throws \Exception in case of general failures
*/
public static function addStreamHandler($logger, $stream, $level = LogLevel::NOTICE)
{
if ($logger instanceof Monolog\Logger) {
$fileHandler = new Monolog\Handler\StreamHandler($stream, Monolog\Logger::toMonologLevel($level));
$formatter = new Monolog\Formatter\LineFormatter("%datetime% %channel% [%level_name%]: %message% %context% %extra%\n");
$fileHandler->setFormatter($formatter);
$logger->pushHandler($fileHandler);
} else {
throw new InternalServerErrorException('Logger instance incompatible for MonologFactory');
}
}
/**
* This method enables the test mode of a given logger
*
* @param LoggerInterface $logger The logger
*
* @return Monolog\Handler\TestHandler the Handling for tests
*
* @throws InternalServerErrorException if the logger is incompatible to the logger factory
*/
public static function enableTest($logger)
{
if ($logger instanceof Monolog\Logger) {
// disable every handler so far
$logger->pushHandler(new Monolog\Handler\NullHandler());
// enable the test handler
$fileHandler = new Monolog\Handler\TestHandler();
$formatter = new Monolog\Formatter\LineFormatter("%datetime% %channel% [%level_name%]: %message% %context% %extra%\n");
$fileHandler->setFormatter($formatter);
$logger->pushHandler($fileHandler);
return $fileHandler;
} else {
throw new InternalServerErrorException('Logger instance incompatible for MonologFactory');
}
}
}