What's the idiomatic way to do general logging in PHP?

1.3k views Asked by At

Coming from a Java background, I'm used to logging frameworks like log4j, logback and slf4j. However, when doing PHP programming, I find my self using echo and var_dump/print_r and write logging information to (usually) the web pages I'm working with. I'm thinking that there must be a better way to do this in PHP as well? So what is the idiomatic way to do PHP logging?

I've come across log4php, and some places suggest to use error_log also for general logging purposes. What complicates matter further is that the PHP code I write usually are modules in a larger system, so multiple modules may run within the same request, and logging should preferably be isolated per module.

Any input and suggestions are appreciated.

1

There are 1 answers

6
Sven On

I've been a long time user of Log4PHP, and I can highly recommend it. :)

But the question about doing proper logging is rather difficult. I use Log4PHP in an enterprise environment where there are multiple applications that all use the same logging, and they also assume that the logger is correctly configured and ready to use. So it's basically a very easy "I assume the same logging is available everywhere" situation.

Developing modules for others to use is a completely different task. You could possibly use your own internal logging, but where do you write those log messages to? It can be considered bad behavior if your module unexpectedly fills the hard drive. It would also be a requirement for your module to log to that target that the rest of the application is logging to.

If your module is small enough, logging might not be a really big issue, because you would be able to communicate any error situations by other means (like throwing exceptions or returning false and offer a dedicated error info function).

There is a definition of a common logger interface that all logging frameworks might eventually implement: PSR-3 But two drawbacks will make this an unavailable solution for you: 1. Log4PHP does not currently implement that interface, and 2. it uses namespaces and so requires PHP 5.3 at least.

The general thought behind it might help you, though: Your module should offer a way to accept a logger that is passed into it from the outside world. If there is no logger, it should not log. And because you might want to test your logging, there should be wrapper that present a uniform interface to your modules and encapsulate the nasty implementation differences of any loggers. Start offering a PSR-3-Wrapper and a Log4PHP wrapper for your modules and react to public demand for other log requirements.