1
0
mirror of https://github.com/danog/MadelineProto.git synced 2024-12-02 13:57:46 +01:00
MadelineProto/src/Logger.php

462 lines
14 KiB
PHP
Raw Normal View History

2022-12-30 21:54:44 +01:00
<?php
declare(strict_types=1);
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
/**
* Logger module.
*
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
2023-01-04 12:43:01 +01:00
* @copyright 2016-2023 Daniil Gentili <daniil@daniil.it>
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
2019-10-31 15:07:35 +01:00
* @link https://docs.madelineproto.xyz MadelineProto documentation
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
*/
2018-02-24 17:54:39 +01:00
2016-08-08 18:10:13 +02:00
namespace danog\MadelineProto;
2016-08-08 18:10:28 +02:00
use Amp\ByteStream\Pipe;
2023-01-04 15:26:06 +01:00
use Amp\ByteStream\WritableResourceStream;
use Amp\ByteStream\WritableStream;
use danog\Loop\Loop;
use danog\MadelineProto\Settings\Logger as SettingsLogger;
2020-09-26 17:11:41 +02:00
use Psr\Log\LoggerInterface;
2022-12-30 21:43:58 +01:00
use Revolt\EventLoop;
2022-12-30 19:21:36 +01:00
use Throwable;
2023-01-20 14:36:21 +01:00
use Webmozart\Assert\Assert;
2022-12-30 19:21:36 +01:00
use const DEBUG_BACKTRACE_IGNORE_ARGS;
use const DIRECTORY_SEPARATOR;
2020-07-09 20:53:01 +02:00
2022-12-30 19:21:36 +01:00
use const E_ALL;
use const FILE_APPEND;
use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_SLASHES;
use const PATHINFO_DIRNAME;
use const PHP_EOL;
use const PHP_SAPI;
2023-01-14 20:30:49 +01:00
use function Amp\async;
2019-06-04 14:55:58 +02:00
use function Amp\ByteStream\getStderr;
use function Amp\ByteStream\getStdout;
use function Amp\ByteStream\pipe;
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Logger class.
2019-10-31 12:45:19 +01:00
*/
2023-01-15 12:05:38 +01:00
final class Logger
2016-08-08 18:10:28 +02:00
{
2020-10-15 19:07:37 +02:00
/**
* @internal ANSI foreground color escapes
*/
2023-11-11 16:55:29 +01:00
public const FOREGROUND = ['default' => 39, 'black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'light_gray' => 37, 'dark_gray' => 90, 'light_red' => 91, 'light_green' => 92, 'light_yellow' => 93, 'light_blue' => 94, 'light_magenta' => 95, 'light_cyan' => 96, 'white' => 97];
2020-10-15 19:07:37 +02:00
/**
* @internal ANSI background color escapes
*/
2023-11-11 16:55:29 +01:00
public const BACKGROUND = ['default' => 49, 'black' => 40, 'red' => 41, 'magenta' => 45, 'yellow' => 43, 'green' => 42, 'blue' => 44, 'cyan' => 46, 'light_gray' => 47, 'dark_gray' => 100, 'light_red' => 101, 'light_green' => 102, 'light_yellow' => 103, 'light_blue' => 104, 'light_magenta' => 105, 'light_cyan' => 106, 'white' => 107];
2020-10-15 19:07:37 +02:00
/**
* @internal ANSI modifier escapes
*/
2023-11-11 16:55:29 +01:00
public const SET = ['bold' => 1, 'dim' => 2, 'underlined' => 3, 'blink' => 4, 'reverse' => 5, 'hidden' => 6];
2020-10-15 19:07:37 +02:00
/**
* @internal ANSI reset modifier escapes
*/
2023-11-11 16:55:29 +01:00
public const RESET = ['all' => 0, 'bold' => 21, 'dim' => 22, 'underlined' => 24, 'blink' => 25, 'reverse' => 26, 'hidden' => 28];
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Logging mode.
2019-10-31 12:45:19 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private readonly int $mode;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Optional logger parameter.
2019-10-31 12:45:19 +01:00
*
* @var null|string|callable
2019-10-31 12:45:19 +01:00
*/
2023-01-20 14:36:21 +01:00
private readonly mixed $optional;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Logger prefix.
2019-10-31 12:45:19 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private readonly string $prefix;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Logging level.
2019-10-31 12:45:19 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private readonly int $level;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Logging colors.
2019-10-31 12:45:19 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private array $colors;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Newline.
2019-10-31 12:45:19 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private readonly string $newline;
2020-02-26 12:45:30 +01:00
/**
2020-02-26 14:14:26 +01:00
* Logfile.
2020-02-26 12:45:30 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private readonly WritableStream $stdout;
/**
* Unbuffered logfile.
*
*/
private readonly WritableStream $stdoutUnbuffered;
/**
* @var array<int, list{WritableStream, \Amp\Future}>
*/
private static array $closePromises = [];
2023-01-20 14:36:21 +01:00
/**
* Log rotation loop ID.
*/
private ?string $rotateId = null;
/**
* PSR logger.
*/
private readonly PsrLogger $psr;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Default logger instance.
2019-10-31 12:45:19 +01:00
*/
2023-01-04 15:26:06 +01:00
public static ?self $default = null;
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Whether the AGPL notice was printed.
2019-10-31 12:45:19 +01:00
*
*/
2023-01-20 14:36:21 +01:00
private static bool $printed = false;
/**
* Ultra verbose logging.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const ULTRA_VERBOSE = 5;
/**
* Verbose logging.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const VERBOSE = 4;
/**
* Notice logging.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const NOTICE = 3;
/**
* Warning logging.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const WARNING = 2;
/**
* Error logging.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const ERROR = 1;
/**
* Log only fatal errors.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const FATAL_ERROR = 0;
2020-07-09 20:53:01 +02:00
/**
* Default logger (syslog).
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const DEFAULT_LOGGER = 1;
/**
* File logger.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const FILE_LOGGER = 2;
/**
* Echo logger.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const ECHO_LOGGER = 3;
/**
* Callable logger.
2020-10-15 19:07:37 +02:00
*
* @internal
*/
2023-11-11 16:55:29 +01:00
public const CALLABLE_LOGGER = 4;
2020-10-15 19:07:37 +02:00
/**
* Ultra verbose level.
*/
2023-11-11 16:55:29 +01:00
public const LEVEL_ULTRA_VERBOSE = self::ULTRA_VERBOSE;
2020-10-15 19:07:37 +02:00
/**
* Verbose level.
*/
2023-11-11 16:55:29 +01:00
public const LEVEL_VERBOSE = self::VERBOSE;
2020-10-15 19:07:37 +02:00
/**
* Notice level.
*/
2023-11-11 16:55:29 +01:00
public const LEVEL_NOTICE = self::NOTICE;
2020-10-15 19:07:37 +02:00
/**
* Warning level.
*/
2023-11-11 16:55:29 +01:00
public const LEVEL_WARNING = self::WARNING;
2020-10-15 19:07:37 +02:00
/**
* Error level.
*/
2023-11-11 16:55:29 +01:00
public const LEVEL_ERROR = self::ERROR;
2020-10-15 19:07:37 +02:00
/**
* Fatal error level.
*/
2023-11-11 16:55:29 +01:00
public const LEVEL_FATAL = self::FATAL_ERROR;
2020-10-15 19:07:37 +02:00
/**
* Default logger (syslog).
*/
2023-11-11 16:55:29 +01:00
public const LOGGER_DEFAULT = self::DEFAULT_LOGGER;
2020-10-15 19:07:37 +02:00
/**
* Echo logger.
*/
2023-11-11 16:55:29 +01:00
public const LOGGER_ECHO = self::ECHO_LOGGER;
2020-10-15 19:07:37 +02:00
/**
* File logger.
*/
2023-11-11 16:55:29 +01:00
public const LOGGER_FILE = self::FILE_LOGGER;
2020-10-15 19:07:37 +02:00
/**
* Callable logger.
*/
2023-11-11 16:55:29 +01:00
public const LOGGER_CALLABLE = self::CALLABLE_LOGGER;
2020-10-15 19:07:37 +02:00
2019-06-20 20:21:31 +02:00
/**
2019-09-02 17:08:36 +02:00
* Construct global static logger from MadelineProto settings.
2019-06-20 20:21:31 +02:00
*
* @param SettingsLogger $settings Settings instance
2019-06-20 20:21:31 +02:00
*/
2020-09-22 23:10:56 +02:00
public static function constructorFromSettings(SettingsLogger $settings): self
2019-09-02 17:08:36 +02:00
{
2020-09-24 11:45:20 +02:00
return self::$default = new self($settings);
2019-06-20 20:21:31 +02:00
}
2019-06-20 20:21:31 +02:00
/**
* Construct logger.
2019-10-31 12:45:19 +01:00
*/
public function __construct(SettingsLogger $settings, string $prefix = '')
2016-08-08 18:10:28 +02:00
{
2020-09-26 17:11:41 +02:00
$this->psr = new PsrLogger($this);
2020-04-05 22:22:47 +02:00
$this->prefix = $prefix === '' ? '' : ', '.$prefix;
$this->mode = $settings->getType();
2023-01-22 17:56:14 +01:00
$this->level = $settings->getLevel();
2023-01-20 19:21:13 +01:00
$optional = $settings->getExtra();
$maxSize = $settings->getMaxSize();
if ($this->mode === self::FILE_LOGGER) {
2023-10-01 20:05:04 +02:00
if (!$optional || !file_exists(pathinfo($optional, PATHINFO_DIRNAME))) {
2023-01-20 19:21:13 +01:00
$optional = Magic::$script_cwd.DIRECTORY_SEPARATOR.'MadelineProto.log';
}
2023-10-01 20:05:04 +02:00
if (!str_ends_with($optional, '.log')) {
2023-01-20 19:21:13 +01:00
$optional .= '.log';
}
2023-10-01 20:05:04 +02:00
if ($maxSize !== -1 && file_exists($optional) && filesize($optional) > $maxSize) {
file_put_contents($optional, '');
}
}
2023-01-20 19:21:13 +01:00
$this->optional = $optional;
2023-10-01 20:05:04 +02:00
$this->colors[self::ULTRA_VERBOSE] = implode(';', [self::FOREGROUND['light_gray'], self::SET['dim']]);
$this->colors[self::VERBOSE] = implode(';', [self::FOREGROUND['green'], self::SET['bold']]);
$this->colors[self::NOTICE] = implode(';', [self::FOREGROUND['yellow'], self::SET['bold']]);
$this->colors[self::WARNING] = implode(';', [self::FOREGROUND['white'], self::SET['dim'], self::BACKGROUND['red']]);
$this->colors[self::ERROR] = implode(';', [self::FOREGROUND['white'], self::SET['bold'], self::BACKGROUND['red']]);
$this->colors[self::FATAL_ERROR] = implode(';', [self::FOREGROUND['red'], self::SET['bold'], self::BACKGROUND['light_gray']]);
2024-05-29 21:10:29 +02:00
$newline = PHP_EOL;
2020-07-09 20:53:01 +02:00
if ($this->mode === self::ECHO_LOGGER) {
$stdout = getStdout();
2020-07-09 20:53:01 +02:00
if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
2024-05-29 21:10:29 +02:00
$newline = '<br>'.$newline;
2019-06-04 14:55:58 +02:00
}
2020-07-09 20:53:01 +02:00
} elseif ($this->mode === self::FILE_LOGGER) {
2023-10-01 20:05:04 +02:00
$stdout = new WritableResourceStream(fopen($this->optional, 'a'));
if ($maxSize !== -1) {
2023-01-20 14:36:21 +01:00
$optional = $this->optional;
$stdout = $stdout;
2022-12-30 21:43:58 +01:00
$this->rotateId = EventLoop::repeat(
10,
2023-01-20 14:36:21 +01:00
static function () use ($maxSize, $optional, $stdout): void {
2023-10-01 20:05:04 +02:00
clearstatcache(true, $optional);
if (file_exists($optional) && filesize($optional) >= $maxSize) {
ftruncate($stdout->getResource(), 0);
2023-08-19 21:45:38 +02:00
self::log("Automatically truncated logfile to $maxSize, MadelineProto ".\danog\MadelineProto\API::RELEASE);
2020-07-09 20:53:01 +02:00
}
2022-12-30 19:21:36 +01:00
},
2020-07-09 20:53:01 +02:00
);
2022-12-30 21:43:58 +01:00
EventLoop::unreference($this->rotateId);
2020-07-09 20:53:01 +02:00
}
} elseif ($this->mode === self::DEFAULT_LOGGER) {
2019-09-02 17:08:36 +02:00
$result = @\ini_get('error_log');
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
if ($result === 'syslog') {
$stdout = getStderr();
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
} elseif ($result) {
2023-10-01 20:05:04 +02:00
$stdout = new WritableResourceStream(fopen($result, 'a+'));
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
} else {
$stdout = getStderr();
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
}
}
2024-05-29 21:10:29 +02:00
$this->newline = $newline;
if (isset($stdout)) {
$pipe = new Pipe(PHP_INT_MAX);
$this->stdoutUnbuffered = $stdout;
$this->stdout = $pipe->getSink();
$source = $pipe->getSource();
$promise = async(static function () use ($source, $stdout, &$promise): void {
try {
pipe($source, $stdout);
} finally {
2023-10-01 20:05:04 +02:00
unset(self::$closePromises[spl_object_id($promise)]);
}
});
2023-10-01 20:05:04 +02:00
self::$closePromises[spl_object_id($promise)] = [$this->stdout, $promise];
}
2020-10-17 12:47:05 +02:00
self::$default = $this;
if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
try {
2023-10-01 20:05:04 +02:00
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('error_log', $this->mode === self::FILE_LOGGER
? $this->optional
2021-04-10 22:38:26 +02:00
: Magic::$script_cwd.DIRECTORY_SEPARATOR.'MadelineProto.log');
2023-01-20 14:36:21 +01:00
} catch (Exception) {
$this->logger('Could not enable PHP logging');
}
}
2023-01-14 20:30:49 +01:00
if (!self::$printed) {
self::$printed = true;
2023-11-23 21:49:03 +01:00
$this->colors[self::NOTICE] = implode(';', [self::FOREGROUND['light_gray'], self::SET['bold'], self::BACKGROUND['magenta']]);
2023-07-04 18:19:06 +02:00
$this->logger('MadelineProto '.\danog\MadelineProto\API::RELEASE);
2023-10-01 20:05:04 +02:00
$this->logger('Copyright (C) 2016-'.date('Y').' Daniil Gentili');
2023-01-14 20:30:49 +01:00
$this->logger('Licensed under AGPLv3');
$this->logger('https://github.com/danog/MadelineProto');
2023-11-23 21:49:03 +01:00
$this->colors[self::NOTICE] = implode(';', [self::FOREGROUND['light_gray'], self::SET['bold'], self::BACKGROUND['blue']]);
if (Lang::$currentPercentage !== 100) {
$this->logger(sprintf(Lang::$current_lang['translate_madelineproto_cli'], Lang::$currentPercentage));
}
2023-10-01 20:05:04 +02:00
$this->colors[self::NOTICE] = implode(';', [self::FOREGROUND['yellow'], self::SET['bold']]);
2023-01-14 20:30:49 +01:00
}
2016-08-08 18:10:13 +02:00
}
2023-01-20 14:36:21 +01:00
/**
* Truncate logfile.
*/
public function truncate(): void
{
2023-01-20 14:36:21 +01:00
if ($this->mode === self::FILE_LOGGER) {
Assert::true($this->stdoutUnbuffered instanceof WritableResourceStream);
2023-10-01 20:05:04 +02:00
ftruncate($this->stdoutUnbuffered->getResource(), 0);
}
}
/**
* @internal Internal function used to flush the log buffer on shutdown.
*/
public static function finalize(): void
{
foreach (self::$closePromises as [$stdout, $promise]) {
$stdout->close();
$promise->await();
2023-01-20 14:36:21 +01:00
}
}
2020-07-09 20:53:01 +02:00
/**
* Destructor function.
*/
2020-07-09 21:42:06 +02:00
public function __destruct()
2020-07-09 20:53:01 +02:00
{
if ($this->rotateId) {
2022-12-30 21:43:58 +01:00
EventLoop::cancel($this->rotateId);
2020-07-09 20:53:01 +02:00
}
}
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Log a message.
2019-10-31 12:45:19 +01:00
*
* @param mixed $param Message
* @param int $level Logging level
*/
2023-01-04 15:13:55 +01:00
public static function log(mixed $param, int $level = self::NOTICE): void
2016-08-08 18:10:28 +02:00
{
2019-09-02 17:08:36 +02:00
if (!\is_null(self::$default)) {
2023-10-01 20:05:04 +02:00
self::$default->logger($param, $level, basename(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file'], '.php'));
2019-07-01 13:14:56 +02:00
} else {
2020-04-05 22:22:47 +02:00
echo $param.PHP_EOL;
}
}
2019-10-31 12:45:19 +01:00
/**
2019-10-31 15:06:25 +01:00
* Log a message.
2019-10-31 12:45:19 +01:00
*
* @param mixed $param Message to log
2019-10-31 15:06:25 +01:00
* @param int $level Logging level
2019-10-31 12:45:19 +01:00
* @param string $file File that originated the message
*/
2023-01-04 15:13:55 +01:00
public function logger(mixed $param, int $level = self::NOTICE, string $file = ''): void
2018-04-08 19:54:08 +02:00
{
if ($level > $this->level) {
return;
}
if (Magic::$suspendPeriodicLogging) {
2023-01-14 19:51:23 +01:00
Magic::$suspendPeriodicLogging->getFuture()->map(fn () => $this->logger($param, $level, $file));
return;
2018-03-27 21:31:19 +02:00
}
2023-01-14 20:30:49 +01:00
2020-07-09 20:53:01 +02:00
if ($this->mode === self::CALLABLE_LOGGER) {
EventLoop::queue($this->optional, $param, $level);
return;
}
$prefix = $this->prefix;
2022-12-30 19:21:36 +01:00
if ($param instanceof Throwable) {
2019-06-04 13:49:01 +02:00
$param = (string) $param;
2019-09-02 17:08:36 +02:00
} elseif (!\is_string($param)) {
2023-10-01 20:05:04 +02:00
$param = json_encode($param, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
2018-03-02 01:38:10 +01:00
}
2019-10-31 12:45:19 +01:00
if (empty($file)) {
2023-10-01 20:05:04 +02:00
$file = basename(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file'], '.php');
}
2023-10-01 20:05:04 +02:00
$param = str_pad($file.$prefix.': ', 16 + \strlen($prefix))."\t".$param;
2020-07-09 20:53:01 +02:00
if ($this->mode === self::DEFAULT_LOGGER) {
2023-01-11 18:47:27 +01:00
try {
$this->stdout->write($param.$this->newline);
} catch (\Throwable) {
2023-10-01 20:05:04 +02:00
error_log($param);
2020-07-09 20:53:01 +02:00
}
return;
}
$param = Magic::$isatty ? "\33[".$this->colors[$level].'m'.$param."\33[0m".$this->newline : $param.$this->newline;
2023-01-11 18:47:27 +01:00
try {
$this->stdout->write($param);
} catch (\Throwable) {
2020-07-09 20:53:01 +02:00
switch ($this->mode) {
case self::ECHO_LOGGER:
echo $param;
break;
case self::FILE_LOGGER:
2023-10-01 20:05:04 +02:00
file_put_contents($this->optional, $param, FILE_APPEND);
2020-07-09 20:53:01 +02:00
break;
}
2020-01-31 19:29:43 +01:00
}
2016-08-08 18:10:13 +02:00
}
2020-09-26 17:11:41 +02:00
/**
* Get PSR logger.
*/
public function getPsrLogger(): LoggerInterface
{
return $this->psr;
}
2018-02-24 17:54:39 +01:00
}