log4php will not work properly - php

So I recently discovered that the log4* package was available for PHP and upon seeing this eagerly downloaded the latest from the log4php website and followed the installation instructions. The instructions indicate that one is to download the tar package, untar, and place the following directory in a place of one's choosing: log4php/src/main/php
Therefore I copied the contents of log4php/src/main/php into my lib dir under lib/log4php.
In my script, as required, I required the 'Logger.php' class and indicated a properties file to manage my appenders. The properties file, log4php.properties, is located on my filesystem at "/home1/ioforgec/www/devlab/pnotes/config/log4php.properties".
Here is the logfile content:
#
# Example Logger
#
log4php.appender.EA1 = LoggerAppenderConsole
log4php.appender.EA1.target = STDOUT
log4php.appender.EA1.layout = LoggerLayoutPattern
log4php.appender.EA1.ConversionPattern = "%m"
log4php.appender.EA1.threshold = FATAL
log4php.exampleLogger = FATAL, EA1
So here is a copy of my script that implements (more or less 'wraps' the log4php functionality):
<?php
require_once('/home1/ioforgec/www/devlab/pnotes/lib/log4php/Logger.php');
class LogUtil
{
public $logger;
public $properties_file = "/home1/ioforgec/www/devlab/pnotes/config/log4php.properties";
public static function logExample($msg)
{
Logger::configure($properties_file);
$logger = Logger::getLogger("example");
$logger->debug("Shouldnt see this print because of config max level FATAL");
$logger->fatal($msg);
}
}
?>
In order to test that this is working properly, the following script calls the LogUtil.php shown above:
#!/usr/bin/php
<?php
require_once("lib/utils/LogUtil.php");
LogUtil::logExample("example message");
?>
So, despite configuring the example logger to format the messages as the plain message, despite setting the level of the logger to a max of FATAL, not only in the logger declaration but also in the threshold command, the print to the console looks to me like the default root logger:
Mon Oct 18 20:30:05 2010,705 [827] DEBUG example - Shouldnt see this print because of config max level FATAL
Mon Oct 18 20:30:05 2010,711 [827] FATAL example - example message
I see the print statement without the plain formatting as specified, and I see two print statements, the debug print (which should never have printed due to the setting of FATAL on the logger config - FATAL is MUCH higher than DEBUG)
What on earth am I doing wrong? Ive tried every combination of setup I can possibly think of. Does anyone have any suggestions?
Edit - Update - This is still an issue. No progress.
Edit2 - Really? Has no one on this forum tried to use this very popular logging package and its incarnation as a PHP module?
I have tried every conceivable avenue to try and get my question answered, including the log4php user's mailing list.

After many many more hours of manipulating the configuration file I have discovered a small, yet critically important factoid. In order to specify a 'logger' you must name it under the 'logger' hierarchy and its appenders under the 'appender' hierarchy, etc etc. For example:
# for the 'console' logger named 'example' we first define the appender:
log4php.appender.consoleAppender = LoggerAppenderConsole
log4php.appender.consoleAppender.target = STDOUT
log4php.appender.consoleAppender.layout = LoggerLayoutSimple
# we then assign the appender and the minimum log level to the logger:
log4php.logger.example = WARN, consoleAppender
My mistake was in seeing the root logger hierarchy name 'log4php.rootLogger' and assuming that in order to assign a logger one need only name a value for 'log4php.lognameLogger'. Sadly this is no excuse as there was an example, buried, in the documentation. I suppose finding it at 9+ hours is better than not at all :)
Thanks to those who reminded me that there was more debugging work to be done, I appreciated the reminder to keep trying

Related

Natively profile multiple scripts in PHP7

Since the release of PHP 7 it is now not possible to profile an entire selection of scripts using declare(ticks=1) in your base file and then using register_tick_function() to monitor each tick as it no longer follows include paths. According to the PHP bug filed at https://bugs.php.net/bug.php?id=71448 this will never be available again in PHP 7.
Due to an implementation bug, the declare(ticks=1) directive leaked into different compilation units prior to PHP 7.0. This is not how declare() directives, which are per-file or per-scope, are supposed to work.
Are there any alternatives to this approach using native PHP (not C or pear extensions etc.) that are available to me in PHP 7 that will allow me to profile each function or file called in a page load, getting details of the actual file path at least.
My original question that led to finding the bug can be found at How to avoid redeclaring ticks on every file in PHP 7, this question is now about alternative methods.
One common way to do this without declare(ticks=1) is to use a profiler. A profiler will take notice of any method/function called, file loaded etc. and even take timing information so you not only can say which function was called when and by what code and which files were opened but also which part of the program took how long.
A well known profiler in PHP comes with the famous Xdebug extension. It also ships with a debugger:
https://xdebug.org/
One benefit is that you don't need to change the code to do the profiling, it is just the PHP configuration you need to adopt so you can switch it on and off as you need it (e.g. debug / profiling session).
PHP Userland (tick function)
As a work-around not having declare(ticks=1); at the beginning of each file (after #71448), it is possible to add this on-the-fly via a stream-wrapper on the file protocol (for files in the local file-system which is common) that injects it.
This is technically feasible by creating a stream-wrapper that is registered on the file protocol to proxy standard file i/o operations. In this PoC (Gist on Github) the bare-minimum implementation is shown to demonstrate that it works for includes. When test.php is executed and despite that other.php has not declare(ticks=1); in it on disk, the registered tick function is called on the include as the print of the backtraces show:
...
tick_handler() called
#0 tick_handler(1) called at [/home/hakre/stream-wrapper-default-files/test.php:18]
#1 tick_handler() called at [/home/hakre/stream-wrapper-default-files/other.php:2]
#2 include(/home/hakre/stream-wrapper-default-files/other.php) called at [/home/hakre/stream-wrapper-default-files/test.php:24]
...
The output is generated from the registered tick function (here: test.php):
<?php
/**
* Inject declare ticks on include
*/
declare(ticks=1);
require __DIR__ . '/streamwrapper.php';
FileStreamWrapper::init();
// using a function as the callback
register_tick_function('tick_handler', true);
// Function which is called on each tick-event
function tick_handler()
{
echo "tick_handler() called\n";
debug_print_backtrace();
}
register_tick_function('tick_handler');
include "other.php";
include "another.php"; # file does not exists
The stream wrapper in the gist example has only implemented as little as needed to work for the two include statements, as PHP scripts normally do more file i/o it needs to be extended as needed. When it goes about seeking etc., the dynamic insertion needs to be taken into account etc. but there is state per file operation (handle) as there is one instance per each one so this should be well encapsulated. The global state is used for registering/unregistering the stream wrapper for each operation to proxy into the real file-system functions as otherwise it creates endless recursion (wrapper uses the wrapper uses the wrapper ...). The PoC so far shows how it works on principle.
This can be (mis-)used for other things as well, but this PoC is for your specific declare ticks and include use-case.

Laravel Mailing Error

Not long ago I started receiving this strange error with mail sending in my Laravel application, error is:
ErrorException in EsmtpTransport.php line 55:
Argument 1 passed to Swift_Transport_EsmtpTransport::__construct() must implement interface Swift_Transport_IoBuffer, none given
Interesting thing is that my mailing system worked just fine for about a year, nothing has been updated (just server and domain paid again few weeks back), so I presume that code isn't the problem, I double checked information in mail authentication system, those are right too.
I followed exception stack trace, and found that in Swift_SmtpTransport::__construct() parameters are sent right, but from there Swift_EsmtpTransport::__construct() is called without parameters (which is actually error shown)
Also I updated all my libraries (with "composer update" command). I have no idea what can be wrong, and couldn't find anything that helps online, so any help will be great
Current versions are:
"laravel/framework": "5.2.*" // from "composer.json"
"swiftmailer/swiftmailer": "~5.1" (v5.4.6 after update) // from "laravel/framework/composer.json"
--- Edit ---
I found somewhere that this is some kind of loading (Dependency Injection) problem, so I executed this line of code:
var_dump(Swift_DependencyContainer::getInstance()->createDependenciesFor('transport.smtp'));
And got this as result array(0) { }
If anyone is interested, I found answer (with friends help). Problem is incompatibility with PHP version, apparently SwiftMailer library doesn't work on newer versions of PHP (>5.5.9, maybe few versions up, not sure from which version it start failing).
Fail is because of some auto-loading conflicts. Solution to this problem is reverting from lazy load to preload, that will slow down a little bit response time, but in most cases you won't even notice that (in my case, I don't see any decline in performance).
Concrete solution:
Find %APP%/vendor/swiftmailer/swiftmailer/lib/swift_requied.php and change it to look like this
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* Autoloader and dependency injection initialization for Swift Mailer.
*/
if (class_exists('Swift', false)) {
return;
}
// Load Swift utility class
require __DIR__.'/classes/Swift.php';
if (!function_exists('_swiftmailer_init')) {
function _swiftmailer_init()
{
require __DIR__.'/swift_init.php';
}
}
// Start the autoloader and lazy-load the init script to set up dependency injection
// Swift::registerAutoload('_swiftmailer_init');
_swiftmailer_init();
Difference is in last line, Swift::registerAutoload('_swiftmailer_init'); is commented out, and _swiftmailer_init method is called directly.
Hope this helps someone, because I lost about 2 days trying to fix this.

Laravel 5 > Using monolog introspection processor

I have configured Laravel 5 to use a custom logging configuration (default is way too simple). I've added monolog's IntrospectionProcessor to log the file name and line number of the log call.
The problem is that all lines get the same file and line number:
[2015-06-29 17:31:46] local.DEBUG (/home/vagrant/project/vendor/laravel/framework/src/Illuminate/Log/Writer.php#201): Loading view... [192.168.10.1 - GET /loans/create]
Is there a way to config the IntrospectionProcessor to print the actual lines and not the facade ones?
If I do Log::getMonolog()->info('Hello'); it works and prints the correct file and line number... but I don't know how safe is to avoid calling the Writer.writeLog function because it fires a log event (is it safe to not fire that event?).
(Only tried in Laravel 4.2!)
When pushing the Introspection Processor to Monolog it is possible to give an skipClassesPartial array as second parameter in the IntrospectionProcessor contructor. With this array it is possible to skip the Laravel Illuminate classes and the logger logs the class calling the log method.
$log->pushProcessor(new IntrospectionProcessor(Logger::DEBUG, array('Illuminate\\')));
also see: https://github.com/Seldaek/monolog/blob/master/src/Monolog/Processor/IntrospectionProcessor.php
I know this is an old question but I thought I'd give a quick update because it's pretty easy to get this done now.
I haven't tried with Laravel but My own logging mechanism is within a LoggingService wrapper class. As such the introspection was only giving details about the service rather than the caller.
after reading Matt Topolski's answer, I had a look in the IntrospectionProcessor.php. the constructor looks like this:
__construct($level = Logger::DEBUG, array $skipClassesPartials = array(), $skipStackFramesCount = 0)
All I had to do was add the processor like this:
log->pushProcessor(new IntrospectionProcessor(Logger::DEBUG, array(), 1));
This is actually the expected functionality unless you're having the handler process the logs directly (check out the comments at the top of IntrospectionProcessor.php). My guess is you have a wrapper function around the logger and you're calling it from Writer.php -- BUT
If you look at the code for IntrospectionProcessor.php you'll see a bit of code on lines 81 to 87 that decides how to format that stack trace, and it still has access to the stack. If you bump the $i values for $trace[$i - 1] / $trace[$i] up one (aka $trace[$i]/$trace[$i + 1] respectively) you can 'climb' the stack back to where you want.
It's important to note that the 'class' and 'function' parts of the trace need to be one level of the stack higher than the 'file' and 'line.'
On a personal (plz dont mod me bruhs) note, I'd like to see functionality to include a stack offset when throwing the log in. I know what function I want to blame if an error shoots out when I write the error_log('ut oh') but I might(will) forget that by the time the 'ut oh' comes.

Reloading a Class

I have a PHP daemon script running on the command line that can be connected to via telnet etc and be fed commands.
What it does with the command is based on what modules are loaded, which is currently done at the start. (psuedocode below for brevity)
$modules = LoadModules();
StartConnection();
while(true){
ListenForCommands();
}
function LoadModules(){
$modules = Array();
$dir = scandir("modules");
foreach($dir as $folder){
include("modules/".$folder."/".$folder.".php");
$modules[$folder] = new $folder;
}
}
function ListenForCommands(){
if(($command = GetData())!==false){
if(isset($modules[$command])){
$modules[$command]->run();
}
}
}
So, an example module called "bustimes" would be a class called bustimes, living in /modules/bustimes/bustimes.php
This works fine. However, I'd like to make it so modules can be updated on the fly, so as part of ListenForCommands it looks at the filemtime of the module, works out if it's changed, and if so, effectively reloads the class.
This is where the problem comes in, obviously if I include the class file again, it'll error as the class already exists.
All of the ideas I have of how to get around this problem so far are pretty sick and I'd like to avoid doing.
I have a few potential solutions so far, but I'm happy with none of them.
when a module updates, make it in a new namespace and point the reference there
I don't like this option, nor am I sure it can be done (as if I'm right, namespaces have to be defined at the top of the file? That's definitely workaroundable with a file_get_contents(), but I'd prefer to avoid it)
Parsing the PHP file then using runkit-method-redefine to redefine all of the methods.
Anything that involves that kind of parsing is a bad plan.
Instead of including the file, make a copy of the file with everything the same but str_replacing the class name to something with a rand() on the end or similar to make it unique.
Does anyone have any better ideas about how to either a) get around this problem or b) restructure the module system so this problem doesn't occur?
Any advice/ideas/constructive criticism would be extremely welcome!
You should probably load the files on demand in a forked process.
You receive a request
=> fork the main process, include the module and run it.
This will also allow you to run several commands at once, instead of having to wait for each one to run before launching the next.
Fork in php :
http://php.net/manual/en/function.pcntl-fork.php
Tricks with namespaces will fail if module uses external classes (with relative paths in namespace).
Trick with parsing is very dangerous - what if module should keep state? What if not only methods changed, but, for example, name of implemented interface? How it will affect other objects if they have link to instance of reloaded class?
I think #Kethryweryn is something you can try.

PHP Function Scope Failure

I am struggling to understand scope and what's preventing my new code from working (assuming it is a scope issue).
The following function is in a file PATH.'/includes/custom-functions.php' that references a class:
function infusion() {
require_once(PATH.'/classes/infusion.php'); //PATH is defined in WordPress from ~/wp-content/themes/theme/
return new infusion();
}
The class is reliant on PATH.'/api/isdk.php' and connection credentials from another file within /api/ directory. From within PATH .'/includes/custom-functions.php', I have many other functions that call $infusion = infusion(); and work perfectly.
PROBLEM
I have created a new file: PATH.'/includes/report.php' which I need to access $infusion = infusion();but can't get to work by either repeating the function infusion() definition from above; using require_once();; or using include();. All 3 of those options simply kill the rest of the code and I can only come to the conclusion - well, I have no conclusion.
Any help would be greatly appreciated.
I'm assuming the code isn't using namespaces, therefore you aren't permitted to redeclare the infusion function (either by redefining the function, or re-including the class).
Your includes/report.php file should simply have:
require_once PATH.'/includes/custom-functions.php';
// your other code here ...
$infusion = infusion();
It may be the case that other files / classes that you're including in your file are already requiring custom-functions.php along the line, so you may be able to skip that entirely. Also note that the PATH constant should have already been defined somewhere (either directly or via an included file) before you attempt to use it. If you set your error_reporting to include E_ALL, you'll get a notification in your error log if that constant doesn't exist.
If that fails, your error log(s) may provide some additional background on what your issue is.

Categories