Skip to content
Advertisement

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 🙂

Advertisement

Answer

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->log_name=$log_name;

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

    $this->log_file='/your/directory/'.$this->log_name;
    $this->log=fopen($this->log_file,'a');
    }
  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");
    fclose($this->log);
    }
  }

 $log=new Log('file_name','my_php_page');
 $log->log_msg('fizzy soda : 45 bubbles remaining per cubic centimeter');
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement