log4php + PHP 7 - catching and logging Throwable

1.1k views Asked by At

I am having trouble logging a "TypeError" with log4php. I suspect this is because I recently upgraded from php 5.5 to 7.1.

Usually, my syntax looks like this:

<?

use Logger;

class MyClass
{
    /** @var Logger */
    private $logger;

    function __construct(array $configParams)
    {
        Logger::configure('logger.xml');
        $this->logger = Logger::getLogger(__CLASS__);
    }

    public function dostuff()
    {
        try
        {
            // ...
        }
        catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex);
        }
    }
}

?>

The above syntax will print lots of info to the log file, including a stack trace. However after reading the latest php7 docs, I believe I'm meant to handle the \Throwable interface, in order to catch both errors and exceptions (which is great). So I replace the above catch with the following:

catch (\Throwable $ex)

This still prints stack-trace information for my exceptions, but when a "TypeError" is caught, nothing gets printed to the log file.

I assume that this is due to log4php not knowing how to log errors. How can I log errors using log4php in a universal way?

Thanks,

3

There are 3 answers

1
Vahe Galstyan On

I think you should use $ex->getMessage() for error() method your code should be

 catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex->getMessage());
        }

For logging trace you should use trace

 catch (Exception $ex)
            {
                $this->logger->trace("ERROR CAUGHT", $ex);
            }
1
sensorario On

Try to fix this

$this->logger->error("ERROR CAUGHT", $ex);

with

$this->logger->error("ERROR CAUGHT : " . $ex->getMessage()); 

log4php's documentation says that error method has just one parameter.

0
Dimitar Darazhanski On

It took me a while to figure out why the original file name and line number was not logged by log4php when an exception is thrown. It turned out that my custom exception_handler class was only logging the exception message (by doing $exception->getMessage()), which does not contain the file name nor the line number. All I to do is concatenate that info: $exception->getFile() and $exception->getLine():

public function exception_handler ($exception) {
        $logger = Logger9::create();
        $logger->info($exception->getMessage()." ".$exception->getFile()." ".$exception->getLine());
}

Don't forget to register the custom handler:

@set_exception_handler(array($this, 'exception_handler'));