Advertisement
Guest User

Untitled

a guest
Mar 1st, 2012
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. /**
  2. Logger class - add messages to log.
  3. Usage
  4. logger::error('some error message');
  5. logger::notice('some notice message');
  6. **/
  7. class logger {
  8.  
  9. const OUTPUT_DISABLED = 0; // 00
  10. const OUTPUT_TO_FILE = 1; // 01
  11. const OUTPUT_TO_SCREEN = 2; // 10
  12.  
  13. //
  14. // define dynamic functions call (like 'fatal', 'error', 'info', etc).
  15. // logger::error('some error messages'); // the message will be added to 'error's array
  16. //
  17. // to get all the messages (array), just call the function without parameters:
  18. // $fatal_messages_array = logger::error();
  19. //
  20. public static function __callStatic($func, $args) {
  21. if (empty($args)) {
  22. return array_key_exists($func, self::$messages) ? self::$messages[$func] : array();
  23. } else {
  24. self::add_message($func, implode($args));
  25. }
  26. }
  27.  
  28. // possibility to set the output to a file
  29. public static function set_output($output_type, $filename = null) {
  30. self::$output_destination = $output_type;
  31. self::$filename = $filename;
  32. }
  33.  
  34. //**--------- PROTECTED -----------**//
  35.  
  36. // logger output properties
  37. protected static $filename = null;
  38. protected static $output_destination = self::OUTPUT_TO_SCREEN;
  39.  
  40. // logger messages
  41. protected static $messages = array();
  42. protected static function add_message($type, $msg) {
  43. $type = strtolower($type);
  44.  
  45. // check the messages array for the type
  46. if (!array_key_exists($type, self::$messages)) {
  47. self::$messages[$type] = array();
  48. }
  49.  
  50. // add the message to it's type
  51. self::$messages[$type][] = $msg;
  52. // output the message to a file / screen / both
  53. self::_output_message($type, $msg);
  54. }
  55.  
  56. // write message to file in the next format:
  57. // [date] ([type]): [message]
  58. protected static function _output_message($type, $msg) {
  59. // generate the log message
  60. $log_message = self::_get_log_message($type, $msg);
  61.  
  62. // check that the file name was defined, and there is a permission to write to file
  63. if (!is_null(self::$filename) && (self::$output_destination & self::OUTPUT_TO_FILE)) {
  64. @file_put_contents(self::$filename, $log_message, FILE_APPEND);
  65. }
  66.  
  67. // check the permission to output to the screen (stdout)
  68. if (self::$output_destination & self::OUTPUT_TO_SCREEN) {
  69. echo $log_message, '<br/>';
  70. }
  71. }
  72.  
  73. protected static function _get_log_message($type, $msg) {
  74. return date('d.m.Y H:i:s').' ('.$type.'): '.$msg."\r\n";
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement