How to implement php logging correctly?

Suppose the file runs every minute on crown. Each time a new file is created. How to make rotation assume a day long?

  • use logrotate. for an application, it will simply look like stuffing the same file with logs, and he will take care of the rest. - etki

3 answers 3

The problem is, in determining when to create a new file, or to add an entry to the end of the file, and not to create / overwrite a new one every time? Or maybe in the fact that the file should, in principle, be one, but all entries should go there and not be erased?

Algorithm:

1) Determine which day is now
2) Set file name
3) Make a record in it. If this file does not exist, a new one will be automatically created.

If you need 1 log file = 1 day :

// Π€ΠΎΡ€ΠΌΠΈΡ€ΡƒΠ΅ΠΌ сообщСниС ΠΈ имя Ρ„Π°ΠΉΠ»Π° $message = "ВСст сообщСния\r\n"; $file_name = date("Y_m_d")."_log.log" // Π—Π°ΠΏΠΈΡΡŒ Π² Ρ„Π°ΠΉΠ» $file = fopen("logs/$file_name", 'a+'); fwrite($file, $message); 

If you need to have one file and not create a new one for each day, then assign the following values ​​to variables:

 // Π€ΠΎΡ€ΠΌΠΈΡ€ΡƒΠ΅ΠΌ сообщСниС ΠΈ имя Ρ„Π°ΠΉΠ»Π° $message = date("Y_m_d")."##ВСкст сообщСния\r\n"; $file_name = "log_file.log"; // Π—Π°ΠΏΠΈΡΡŒ Π² Ρ„Π°ΠΉΠ» ... 

Writing to a file using PHP:

 // Π€ΠΎΡ€ΠΌΠΈΡ€ΡƒΠ΅ΠΌ сообщСниС ΠΈ имя Ρ„Π°ΠΉΠ»Π° ... // Π—Π°ΠΏΠΈΡΡŒ Π² Ρ„Π°ΠΉΠ» error_log($message, 3,"logs/".$file_name); 

Syslog protocol

PHP also has functions that implement sending messages to the system log.

  • openlog (); - opens for the program a connection to the system log
  • syslog (); - generates and sends a message to the system log
  • closelog (); - closes the connection to the system log
  • Plus the problem is that every day you create your own file - Naumov
  • @Naumov Ie A new file should NOT be created? Or vice versa 1 day = 1 file? - RostD

In a nutshell, it looks like http://php.net/manual/ru/function.error-log.php error_log($mymessage) and syslog does the rest

With krone, you can send output in the same syslog like this

 cron.php | syslog -t mycron -p warning 

and configure the syslog.conf file to filter messages and send logs to a specific file.

P.C. About the second option it is necessary to read the docks will be ...

  • can all the same word rotation in the question is more important? - des1roer

As an option, write all the logs in any DBMS (MySQL. On the last SQLite). And there is already a sampling method to display the necessary information through a web interface or PHP-script.

If you need it in the files, then take the file name in the date format (yyyy-mm-dd.log) and add new data to the end. But it all depends on your chosen logger.