We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Logging to file efficiently

The logging to file page, https://docs.phalcon.io/en/3.0.1/reference/logging.html, does not provide much information on how you might use loggong for recording unusual events in an active Web site. How do you make it available efficiently for irregular use?

I have a need to log some activity and the Phalcon log to file would be the best starting point, using mostly Phalcon code instead of my own code. I am thinking of making the logging available as a service so that it is always available anywhere. While the log would not be used in many page views, when it is used, it can be in any page and used several times.

What would be the easiest way to configure it in one place and grab it in any code?

If I start it in service.php, how do I access ->log() in somewhere like indexAction()?



9.7k
edited Jun '17

Started using the following code after some experiments. I now understand how the services are supplied to code.

The outer brackets are there to force the display into code mode.

{

services.php:

use Phalcon\Logger;
use Phalcon\Logger\Adapter\File as LogFileAdapter;
$di->set("logger", function() use ($config)
    {
    $logger = new LogFileAdapter(APP_PATH . $config->application->logPath);
    return $logger;
    });

actionIndex():
$this->logger->info('indexAction() x: ' . $x);

}


145.0k
Accepted
answer

You should really use shared service most likely.

Well in controller accessing using $this->logger it will be no difference, but for example accessing it somewhere else with $di->get() with not shared will cause to create new instance.



9.7k

I read the documentation then looked in the Di code to find setShared. I used setShared and everything works. Changed another service to shared now that I understand the difference.



16.3k
edited Jun '17

See if this code helps. https://github.com/mruz/base-app/blob/8b2c089c56014651833c80c5acb68ff7113b8e2d/app/Bootstrap.php#L463

This is from base-app, a layer built on top of phalcon by @mruz. Will check if I can find some example of how its called. The function should give you a good idea though.