WordPress – write custom php log to separate file

Why write php log to separate file

Using default php error log in wordpress php code for informational messages can pollute php error log file. This can cause us to miss out important system php error and warnings in php error log. So it is better to write informational messages in a separate custom log.

Steps to create separate log for wordpress code

We’ll use Ubuntu Linux for this purpose of this tutorial.

  1. To create separate log for wordpress code, make sure /var/log folder is writable by www-data.

    $ sudo chmod 777 /var/log
    
  2. Use the following code snippet to log informational messages from wordpress php code:

    <?php
    function my_wordpress_log ($str) {
      error_log("$str", 3, "/var/log/wordpress.log");
    }
    my_wordpress_log("custom message here\n");
    ?>
    

    This will cause /var/log/wordpress.log to be created initially and later logs will be appended to it.

  3. Ensure that log is created:

    $ tail -f /var/log/wordpress.log
    
  4. Depending upon your traffic, you may want to either delete/move old log file or rotate it using Linux tools like logrotate.

Adding php error_log style date to custom wordpress log

To add php error_log style date to custom wordpress log, you can use the following code:

function my_wordpress_log ($str) {
  $d = date("j-M-Y H:i:s e");
  error_log("[$d] $str", 3, "/var/log/wordpress.log");
}
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments