NYCPHP Meetup

NYPHP.org

[nycphp-talk] Logging best practices, 1 of 2

Gary Mort garyamort at gmail.com
Thu May 8 18:01:33 EDT 2014


On 05/06/2014 09:39 AM, Federico Ulfo wrote:
>
> Hi PHPers,
>
> ...
> For PHP we'll probably use Monolog, someone suggested to use it 
> wrapped into helper functions such as sail_info(), sail_debug(), 
> sail_error(), sail_warn(), I'm personally skeptical for this solution 
> because not too maintainable, but I agree that Monolog is too verbose 
> and quite ugly to remember.
>
> What's your experience with logging? Is there anything that you could 
> suggesting to do and (especially) not to do when organizing the logs?

I really don't like to directly use custom logging classes/functions.   
You become locked into a specific framework and switching to the new 
"flavor of the month" in the future is a large workload for little gain.

For informational logging, I prefer to use the functions built in to PHP:
user_error with E_USER_WARNING, E_USER_NOTICE, and E_USER_DEPRECATED.  
Your guaranteed that the function is /always/ available and there are a 
number of options on where to send the log messages.
If you want to use a system like monolog, you can still do that while 
using the user_error function, simply use the set_error_handler function 
and you can route the error message to whatever flavor of the month 
logging class is popular.

If you need more information then is easily contained in a string, then 
in your error handler you can use  serialize it from the extra 
parameters or use $errcontext to get more information.
**code**
functionhandler($errno,$errstr,$errfile,$errline, $errcontext)
{
$errObject = new \StdClass;
$errObject->msg = $errstr;
$errObject->file = $errfile;
$errObject->line = $errline;
if (isset($errcontect['this'])
{
$errObject->classname = get_class($errcontect['this']);
}
$logMsg = json_encode($errObject);
\Fancy\Schmancy\Logging\Tool::log($logMsg);
return true;
}

**endcode**

For ending program execution abrubtly, by the same token I prefer to use 
the tools built into PHP:
user_error with E_USER_ERROR.  Again you have all the options above.

For libraries where I want to maintain flexibility, I prefer to combing 
information logging with throwing exceptions.   That way the message is 
saved/logged regardless, and then whatever script is calling mine can 
either catch the error and recover, or not as is appropriate.


Anytime there is a handler/wrapper option in PHP that can be used to 
provide the custom functionality I want, I prefer to use the use that.  
That way my PHP code is insulated from 'flavor of the month' and api 
changes - while at the same time a small initialization script allows me 
to make full use of them.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20140508/7e9deda8/attachment.html>


More information about the talk mailing list