<?php /** * Description: * Functions to save log into file. * * History: * Created by Moky @ 2009-04-21 */ /* //-- Usage: include_once('include/magic_log.php'); //magic_log_init('filename.log'); // optional ... magic_log('log message...'); ... //magic_log_flush(); // optional, it will be called automatically at the end */ $g_magic_log_filename = '/tmp/magic_test.log'; $g_magic_log_array = array(); $g_magic_log_maxsize = 1024*1024*4; // 4m $g_magic_log_maxcount = 5; /// if (!defined('FILE_APPEND')) { define('FILE_APPEND', 1); } //int file_put_contents ( string filename, string data [, int flags [, resource context]] ) if (!function_exists('file_put_contents')) { function file_put_contents($filename, $data, $flags = 0) { $fp = $flags == FILE_APPEND ? @fopen($filename, 'a') : @fopen($filename, 'w'); if (!$fp) return ; if (is_array($data)) { foreach ($data as $item) { fwrite($fp, $item); } } else { fwrite($fp, $data); } fclose($fp); } } function array_to_string($array) { return is_array($array) ? print_r($array, true) : $array; } /// function magic_log_init($filename) { global $g_magic_log_filename; if (!$filename) return ; $g_magic_log_filename = $filename; // change the filename $g_magic_log_array = array(); // chean the log array } function magic_log_push($string) { global $g_magic_log_array; $g_magic_log_array[] = $string; } // add log info function magic_log($log) { if (is_array($log)) $log = array_to_string($log); $now = date('Y-m-d H:i:s'); magic_log_push("[$now] $log/r/n"); } function magic_log_flush() { magic_log_touch(); // check log file size global $g_magic_log_filename, $g_magic_log_array; if (!$g_magic_log_array) return ; if (count($g_magic_log_array) == 0) return ; file_put_contents($g_magic_log_filename, $g_magic_log_array, FILE_APPEND); $g_magic_log_array = array(); // clean the array } // check log file-chain function magic_log_touch($order = 0) { global $g_magic_log_filename, $g_magic_log_maxsize, $g_magic_log_maxcount; $order = intval($order); if ($order > 0) { $oldfile = "$g_magic_log_filename.$order"; } else { $oldfile = $g_magic_log_filename; if (!file_exists($oldfile)) { touch($oldfile); // create it return ; } else if (filesize($oldfile) <= $g_magic_log_maxsize) { return ; } } $order++; if ($order >= $g_magic_log_maxcount) { unlink($oldfile); // delete it return ; } // check next $newfile = "$g_magic_log_filename.$order"; if (file_exists($newfile)) { magic_log_touch($order); } rename($oldfile, $newfile); } register_shutdown_function('magic_log_flush'); ?>