How do i save logs in php


How do i save logs in PHP? Is there any “magical” function available in php for doing so, or any library? Or should i have to fopen file everytime and dump in it? I want to save my logs in text file.

Thanks in advance 🙂


I wrote a simple class to do this. Maybe you’ll find it useful.

class Log
  public function __construct($log_name,$page_name)
    if(!file_exists('/your/directory/'.$log_name)){ $log_name='a_default_log.log'; }

    $this->app_id=uniqid();//give each process a unique ID for differentiation

  public function log_msg($msg)
    {//the action
    $log_line=join(' : ', array( date(DATE_RFC822), $this->page_name, $this->app_id, $msg ) );
    fwrite($this->log, $log_line."\n");
  function __destruct()
    {//makes sure to close the file and write lines when the process ends.
    $this->log_msg("Closing log");

 $log=new Log('file_name','my_php_page');
 $log->log_msg('fizzy soda : 45 bubbles remaining per cubic centimeter');

Answered By – JAL

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published