开发者

Equivalent of PHP error_log for info logs?

开发者 https://www.devze.com 2023-04-10 23:36 出处:网络
I use error_log for my log开发者_StackOverflow社区ging, but I\'m realizing that there must be a more idiomatic way to log application progress.is there an info_log ?or equivalent ?You can use error_lo

I use error_log for my log开发者_StackOverflow社区ging, but I'm realizing that there must be a more idiomatic way to log application progress. is there an info_log ? or equivalent ?


You can use error_log to append to a specified file.

error_log($myMessage, 3, 'my/file/path/log.txt');

Note that you need to have the 3 (message type) in order to append to the given file.

You can create a function early on in your script to wrap this functionality:

function log_message($message) {
    error_log($message, 3, 'my/file/path/log.txt');   
}


The equivalent is syslog() with the LOG_INFO constant:

syslog(LOG_INFO, 'Message');

If you want to use a file (not a good idea because there is no log rotation and it can fail because of concurrency), you can do:

file_put_contents($filename, 'INFO Message', FILE_APPEND);


I would recommend you to use Monolog: https://github.com/Seldaek/monolog

You can add the dependency by composer:

composer require monolog/monolog

Then you can initialize a file streaming log, for an app called your-app-name, into the file path/to/your.log, as follow:

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('your-app-name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

Monolog is very powerful, you can implement many types of handlers, formatters, and processors. It worth having a look: https://github.com/Seldaek/monolog/blob/master/doc/02-handlers-formatters-processors.md

And finally call it like:

// add records to the log
$log->warning('Foo');
$log->error('Bar');

In order to make it global, I recommend you to add it to your dependency injector, if you have one, or use a singleton with static calls.

Let me know if you want more details about this.

0

精彩评论

暂无评论...
验证码 换一张
取 消