tags:

views:

97

answers:

4

Hello,

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 :)

+2  A: 

All depends what you're trying to log. By default you will have an error_log already which is essentially a plain text file. If you're talking about logging events within your code for debugging or tracking activity within a script then you will need to write your own log handler for this but this is very simple. As another poster says you can push content to the error log using the error_log() function but this would make for some very unmanageable log files imv.

seengee
+7  A: 

If you do not want to use an own implementation or just do fopen-stuff you cyn use the built in function error_log('string to log'); . This will write the desired string into the error log of your server software.

Thariama
PHP allows you to configure what the default logger is using the `error_log` php.ini setting: http://php.net/error-log
R. Bemrose
Thanks +1 for extra info.
Ankit Rathod
+5  A: 

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');
Alex JL
Thanks Alex JL, but this sounds new to me `$this->app_id=self::real_unique_string()`. How will process id be useful for logs? How can the process id help me later when i view the logs?
Ankit Rathod
I use process ID to keep where the line is coming from straight. It will be unique per page with the log, so say you have 5 people accessing your page at once - there will be just a flood of lines in the log. The ID it helps you know which lines came from the same process. You could always take that out if you don't need it.
Alex JL
This seems to be an extremely complicated version of PHP's `error_log($msg, 3, $log_name);`
R. Bemrose
@R. Bemrose This just wraps fopen and fclose with some conveniences... I don't see how it could be seen as 'extremely complicated'.
Alex JL
Ok Thank Alex JL. Now i understood.
Ankit Rathod
@R. Bemrose It's not complicated at all. The only thing i didn't understand till now is it the second parameter passed to hash function(`microtime(1).(time()/147))`).
Ankit Rathod
@Alex JL: OK, let me rephrase that. This seems to be an **completely unneccessary** reimplementation of PHP's built-in `error_log($msg, 3, $log_name)` function, or just using php.ini's `error_log` ini setting to send the default error handler to a file and using `error_log($msg)`.
R. Bemrose
+1 for effort of creating own logger class
Thariama
@R. Bemrose No, that's not true. It provides additional convenience like a> checking that the log file exists and providing a default (probably it should check that it's writable, actually) b> automatically adding a process ID, page name, date and newline after your message. I could have used error_log instead of fopen/fwrite/fclose, but it seems rather unsemantic if you're not logging errors. I'd probably wrap error_log like this to provide the aforementioned features either way.
Alex JL
@Nitesh Panchal Honestly, the real_unique_id function is rather superfluous... that part could be replaced with simply uniqid(). That came from some other code I have, actually. I've edited it to make it simpler.
Alex JL
+2  A: 

If you're not into using the PHP Error Handling Functions (http://www.php.net/manual/en/ref.errorfunc.php) that the other replies have mentioned, here is a deadly simple Logger class that I've used before. Standard warnings apply, as I have not used it in a high risk application or on a heavily trafficked site (though it should be fine).

<?
class Logger
{
  private static function addEntry($str)
  {
    $handle = fopen('./services.log', 'a');
    fwrite($handle, sprintf("%s %s\n", date('c'), $str));
    fclose($handle);
  }

  public static function warn($str)
  {
    self::addEntry("WARNING $str");
  }

  public static function info($str)
  {
    self::addEntry("INFO $str");
  }

  public static function debug($str)
  {
    self::addEntry("DEBUG $str");
  }
}
?>

Then you can use it like this:

<?php
require('Logger.php');
Logger::debug('test');
Logger::warn('bwah');
Logger::info('omg');
?>

Very simple to add more functions (like Logger::error()), store the file handler so you don't have to keep re-opening it every time you want to log something (ie., store the $handle variable in a private static class scope variable, and have addEntry() check to see if it's set whenever it's run and run fopen() if it isn't), or change the format of how you're logging.

Cheers.

Sam Bisbee
Very nice Sam, voted. Static functions are nice for this.
Ankit Rathod
Glad you like it, and thanks for the vote. And yes, this is a text book example of when to use static. Cheers.
Sam Bisbee