Source for file Logger.php

Documentation is available at Logger.php

  1. <?php
  2. /**
  3.  * Logger.php
  4.  *
  5.  * PHP version 5
  6.  *
  7.  * LICENSE: This program is free software; you can redistribute it and/or
  8.  * modify it under the terms of the GNU General Public License as published
  9.  * by the Free Software Foundation.
  10.  *
  11.  * @package                     FreeNAC
  12.  * @author                      Hector Ortiz (FreeNAC Core Team)
  13.  * @copyright                   2007 FreeNAC
  14.  * @license                     http://www.gnu.org/copyleft/gpl.html   GNU Public License Version 2
  15.  * @version                     SVN: $Id$
  16. */
  17.  
  18. /**
  19. * Define the Logger class which is a Singleton which provides for logging facilities.
  20. *
  21. * This class uses the constants defined by Syslog, which are listed as follows:
  22. *   - LOG_EMERG   0       System is unusable
  23. *   - LOG_ALERT   1       Action must be taken immediately
  24. *   - LOG_CRIT    2       Critical conditions
  25. *   - LOG_ERR   3       Error conditions
  26. *   - LOG_WARNING 4       Warning conditions
  27. *   - LOG_NOTICE  5       Normal, but significant condition
  28. *   - LOG_INFO    6       Informational message
  29. *   - LOG_DEBUG   7       Debug-level-message
  30. *
  31. * Example usage:
  32. *   - $logger=Logger::getInstance();        Needed, before other lines
  33. *   - $logger->setDebugLevel(3);        Log debug1,2,3 (default is only 1)
  34. *   - $logger->setLogToStdErr();        If you don't want to use syslog
  35. *   - $logger->logit("Hello world");        Will appear in syslog or stderr
  36. *   - $logger->debug("Hello debug world");    Will be prefixed "debug1"
  37. *   - $logger->debug("Hello debug world",3);    Will be prefixed "debug3"
  38. *    
  39. */
  40.  
  41. /* Define some other values for the facility to open
  42.  * The ones defined by default are:
  43.  * LOG_AUTH     32
  44.  * LOG_AUTHPRIV    80
  45.  * LOG_CRON    72
  46.  * LOG_DAEMON    24    
  47.  * LOG_KERN    0
  48.  * LOG_LOCAL0    128
  49.  * LOG_LOCAL1    136
  50.  * LOG_LOCAL2    144
  51.  * LOG_LOCAL3    152
  52.  * LOG_LOCAL4    160
  53.  * LOG_LOCAL5    168
  54.  * LOG_LOCAL6    176
  55.  * LOG_LOCAL7    184
  56.  * LOG_LPR    48
  57.  * LOG_MAIL    16
  58.  * LOG_NEWS    56
  59.  * LOG_SYSLOG    40
  60.  * LOG_USER    8
  61.  * LOG_UUCP    64
  62. */
  63. define('WEB',500);
  64.  
  65. final class Logger
  66. {
  67.    /**
  68.    * Maximum debugging level
  69.    */
  70.    const MAX_DEBUG_LEVEL=3;                
  71.    private $debug_level=NULL;            //Current debugging level
  72.    private static $instance=NULL;        //Instance of this class
  73.    private $identifier=NULL;
  74.    private $facility=NULL;
  75.    private $stderr=false;
  76.    private $stdout=false;
  77.    private $stdout_stream NULL;
  78.    private $stderr_stream NULL;
  79.    private $httpd_log=false;            //Log to webserver log?
  80.    private $email_alert=false;            //Send Err or higher via email
  81.    
  82.    /**
  83.    * Open logging facilities and start output buffering
  84.    */
  85.    private function __construct($facility=LOG_DAEMON)  
  86.    {
  87.       ob_start();
  88.       $this->identifier=basename($_SERVER['SCRIPT_FILENAME'])#Get script's name as identifier
  89.       $this->openFacility($facility);           #Open logging facilities
  90.    }
  91.  
  92.    /**
  93.    * Close logging facilities and flush output buffering
  94.    */
  95.    public function __destruct()        
  96.    {
  97.       ob_end_flush();
  98.       closelog();
  99.    }
  100.  
  101.    /**
  102.    * Divert logging to Email
  103.    * @param boolean $var        Activate or deactivate LogToEmail logging. Default is to activate ($var=true)
  104.    * @return boolean        True if successful, false otherwise
  105.    */
  106.    public function setLogToEmail($var=true)
  107.    {
  108.       if (is_bool($var&& ($var===true))
  109.       {
  110.          $this->email_alert=true;
  111.       }
  112.       else
  113.       {
  114.          $this->email_alert=false;
  115.       }
  116.    }
  117.  
  118.    /**
  119.    * Divert logging to httpd
  120.    * @param boolean $var        Activate or deactivate httpd logging. Default is to activate ($var=true)
  121.    */
  122.    public function setLogToHttpd($var=true)
  123.    {
  124.       if (is_bool($var&& ($var===true))
  125.       {
  126.          $this->httpd_log=true;
  127.       }
  128.       else
  129.       {
  130.          $this->httpd_log=false;
  131.       }
  132.    }
  133.  
  134.    /**
  135.    * Divert logging to StdErr
  136.    * @param boolean $var    Activate or deactivate StdErr logging. Default is to activate ($var=true)
  137.    */
  138.    public function setLogToStdErr($var=true)    //Redirect logging to stderr
  139.    {
  140.       if (is_bool($var&& ($var===true))
  141.       {
  142.          closelog();        #Close syslog
  143.          $this->stderr=true;
  144.       }
  145.       else
  146.       {
  147.          $this->stderr=false;
  148.       }
  149.    }
  150.  
  151.    /**
  152.    * Divert logging to StdOut
  153.    * @param boolean $var        Activate or deactivate StdOut logging. Default is to activate ($var=true)
  154.    */
  155.    public function setLogToStdOut($var=true)    //Redirect logging to stderr
  156.    {
  157.       if (is_bool($var&& ($var===true))
  158.       {
  159.          closelog();            #Close syslog
  160.          $this->stdout=true;
  161.       }
  162.       else
  163.       {
  164.          $this->stdout=false;
  165.       }
  166.    }
  167.  
  168.    /**
  169.    * Set the script name which will be displayed in syslog
  170.    * @param mixed $name        Name to set to
  171.    * @return boolean        True if successful, false otherwise
  172.    */
  173.    public function setIdentifier($name=NULL)    
  174.    {
  175.       if ($name != NULL)
  176.       {   
  177.          closelog();
  178.          $this->identifier=$name;
  179.          return true;
  180.       }
  181.       else 
  182.       {
  183.          return false;
  184.       }
  185.    }
  186.   
  187.    /**
  188.    * The name displayed in syslog
  189.    * @return mixed         Name
  190.    */
  191.    public function getIdentifier()    
  192.    {
  193.       return $this->identifier;
  194.    }
  195.  
  196.    /**
  197.    * Get instance of this class
  198.    * @return object    Current instance
  199.    */
  200.    public static function getInstance($facility=LOG_DAEMON)
  201.    {
  202.       if (empty(self::$instance))               //Is there an instance of this class?
  203.          self::$instance=new Logger($facility);        //No, then create it
  204.       return self::$instance;                   //Yes, return it
  205.    }
  206.  
  207.    /**
  208.    * Prevent clonning the instance
  209.    * @throws    Exception indicating that copy can't be performed
  210.    */
  211.    public function __clone()                   
  212.    {
  213.       throw new Exception("Cannot clone the SysLogger object");
  214.    }
  215.  
  216.    /**
  217.    * Log a message to the HTTPD log
  218.    * This method is a wrapper around the error_log function
  219.    * @return boolean        True if successful, false otherwise
  220.    */
  221.    public function loghttpd($message='')
  222.    {
  223.       return error_log($message,0);
  224.    }
  225.    
  226.    /**
  227.    * Log a message.
  228.    * @param mixed $message        Message to log
  229.    * @param integer $criticality     How critical is this message? Default is informational
  230.    * @return boolean            True if successful, false otherwise
  231.    */
  232.    public function logit($message='',$criticality=LOG_INFO)
  233.    {
  234.       if (($criticality<0|| ($criticality 7))    #Sanity check, defaults to LOG_INFO if user entered an invalid value
  235.          $criticality=LOG_INFO;
  236.       if ($criticality == LOG_ERR)
  237.          $message="ERROR: $message";
  238.       else if ($criticality == LOG_WARNING)
  239.          $message="WARNING: $message";
  240.       if (is_string($message)&&(strlen($message)>0))
  241.       {
  242.          if ($this->stderr)                #Should we log to stderr?
  243.          {
  244.             $message=trim($message);
  245.             $message.="\n";
  246.             if ($this->facility == WEB )
  247.             {
  248.                $fd fopen($this->stderr_stream,'w');
  249.                fputs($fd$message);
  250.                fclose($fd);
  251.             }
  252.             else
  253.             {  
  254.                fputs(STDERR$message);   
  255.                ob_flush();
  256.             }
  257.          }
  258.          else if ($this->stdout)
  259.          {
  260.             $message=trim($message);
  261.             if ($this->facility == WEB )
  262.             {
  263.                $message.="<br />\n";
  264.                $fd fopen($this->stdout_stream,'w');
  265.                fputs($fd$message);
  266.                fclose($fd);
  267.             }
  268.             else
  269.             {
  270.                $message.="\n";
  271.                fputs(STDOUT$message);
  272.                ob_flush();
  273.             }
  274.          }
  275.          else
  276.          {
  277.             syslog((int)$criticality,$message);         #Log it through syslog
  278.             ob_flush();
  279.          }
  280.          if ($this->httpd_log)
  281.          {
  282.             $this->loghttpd($message);            #Should we log to Weblog?
  283.          }
  284.          if ($this->email_alert)
  285.          {
  286.             error_log($message,1,"root");        #TBD: Use a variable for email?
  287.          }
  288.          #if ($this->file_log)
  289.          #{
  290.          #   error_log($message,3,"/var/log/mylog");    #TBD: Use a ariable for mail?
  291.          #}
  292.          return true;
  293.       }
  294.       else
  295.       
  296.          return false;
  297.       }
  298.    }
  299.  
  300.    /**
  301.    * Send an email to root
  302.    * This is a wrapper around the php mail function
  303.    * @return boolean            True is mail successfully sent, false otherwise
  304.    */
  305.    public function mailit($subject,$message,$to='root')
  306.    {
  307.       if (strlen($message0)
  308.       {
  309.          return mail($to$subject$message);
  310.       }
  311.       else
  312.       {
  313.          return false;
  314.       }
  315.    }
  316.  
  317.    /**
  318.    * Wrapper around the logit method. Log a message only if the specified level for this function
  319.    * is less or equal than the current debugging level.
  320.    * @param mixed $msg            Message to log
  321.    * @param integer $to_level        Debug level where this message should be displayed. Default 1.
  322.    * @return boolean            True if successful, false otherwise
  323.    */
  324.    public function debug($msg,$to_level=1)
  325.    {
  326.       if (is_int($to_level)&&is_string($msg))
  327.       {
  328.          #Perform sanity checks to see if both the current debugging level and the specified level are valid values 
  329.          #according to MAX_DEBUG_LEVEL
  330.  
  331.          #Lower bound
  332.          if ($to_level <= 0)
  333.             $to_level=NULL;
  334.          if ($this->debug_level <= 0)
  335.             $this->debug_level=NULL;
  336.  
  337.          #Upper bound
  338.          if ($this->debug_level self::MAX_DEBUG_LEVEL)
  339.             $this->debug_level=self::MAX_DEBUG_LEVEL;
  340.          if ($to_level self::MAX_DEBUG_LEVEL)
  341.             $to_level=self::MAX_DEBUG_LEVEL;
  342.  
  343.          #The specified level falls within our current debugging level?
  344.          if ($this->debug_level && ($to_level<=$this->debug_level&& (strlen($msg)>0))
  345.          {
  346.             $mymsg="Debug$to_level$msg";    #Include debugging level in the message
  347.             $this->logit($mymsg,LOG_DEBUG);    #Log it
  348.             return true;
  349.          }
  350.          else 
  351.          {
  352.             return false;
  353.          }
  354.       }
  355.       else 
  356.       {
  357.          return false;
  358.       }
  359.    }
  360.  
  361.    /**
  362.    * Get the current debugging level.
  363.    * @return integer        Current debug level
  364.    */
  365.    public function getDebugLevel()
  366.    {
  367.       return $this->debug_level;
  368.    }
  369.  
  370.    /**
  371.    * Set debugging level. It will cause to print all debugging messages less or equal than the value we specify in this function.
  372.    * @param integer $var    Debug level. Default 1. 0 means no debugging
  373.    * @return boolean        True if successful, false otherwise
  374.    */
  375.    public function setDebugLevel($var=1)
  376.    {
  377.       if (is_int($var))
  378.       {
  379.          $this->debug_level=$var;
  380.          return true;
  381.       }
  382.       else
  383.       {
  384.          $this->logit("Value passed to setDebugLevel is not an integer",LOG_WARNING);
  385.          return false;
  386.       }
  387.    }
  388.  
  389.    /**
  390.    * Wrapper around the logit method.
  391.    * This method logs by default to the stdout stream defined by the chosen facility
  392.    * @param mixed $error        The error message to display
  393.    * @return boolean            True if successful, false otherwise
  394.    */
  395.    public function showMessage($message=NULL)
  396.    {
  397.       if (strlen($message0)
  398.       {
  399.          $this->setLogToStdOut(true);
  400.          $this->logit($message);
  401.          $this->setLogToStdOut(false);
  402.          return true;
  403.       }
  404.       else
  405.          return false;
  406.    }
  407.  
  408.    /**
  409.    * Wrapper around the logit method.
  410.    * This method logs by default to the stderr stream defined by the chosen facility
  411.    * @param mixed $error    The error message to display
  412.    * @return boolean        True if successful, false otherwise
  413.    */
  414.    public function showError($error=NULL)
  415.    {
  416.       if (strlen($error0)
  417.       {
  418.          $this->setLogToStdErr(true);
  419.          $this->logit($errorLOG_ERR);
  420.          $this->setLogToStdErr(false);
  421.          return true;
  422.       }
  423.       else
  424.          return false;
  425.    }
  426.  
  427.    /**
  428.    * Open logging facility specified for the user
  429.    * @param integer $facility    Facility to open. Default is LOG_DAEMON
  430.    * @return boolean        True if successful, false otherwise
  431.    */
  432.    public function openFacility($facility=LOG_DAEMON)
  433.    {
  434.       if (is_integer($facility))
  435.       {
  436.          switch($facility)                    #Sanity checks
  437.          {
  438.             case LOG_AUTH:
  439.             case LOG_AUTHPRIV:
  440.             case LOG_CRON:
  441.             case LOG_DAEMON:
  442.             case LOG_KERN:
  443.             case LOG_LOCAL0:
  444.             case LOG_LOCAL1:
  445.             case LOG_LOCAL2:
  446.             case LOG_LOCAL3:
  447.             case LOG_LOCAL4:
  448.             case LOG_LOCAL5:
  449.             case LOG_LOCAL6:
  450.             case LOG_LOCAL7:
  451.             case LOG_LPR:
  452.             case LOG_MAIL:
  453.             case LOG_NEWS:
  454.             case LOG_SYSLOG:
  455.             case LOG_USER:
  456.             case LOG_UUCP:
  457.                {
  458.                   closelog();
  459.                   $this->facility=$facility;
  460.                   $this->stdout_stream STDOUT;
  461.                   $this->stderr_stream STDERR
  462.                   return openlog($this->identifier,LOG_CONS LOG_NDELAY LOG_PID$this->facility);
  463.                }
  464.             case WEB:
  465.                {
  466.                   closelog();
  467.                   $this->facility=$facility;
  468.                   $this->stdout_stream "php://output";
  469.                   $this->stderr_stream "php://stderr";
  470.                   return openlog($this->identifier,LOG_CONS LOG_NDELAY LOG_PID$this->facility);
  471.                }
  472.             default:
  473.                return false;
  474.          }
  475.       }
  476.       else
  477.       {
  478.          $this->logit("Value passed to openFacility is not recognized",LOG_WARNING);
  479.          return false;
  480.       }
  481.    }
  482. }

Documentation generated on Mon, 17 Nov 2008 01:10:40 +0100 by phpDocumentor 1.4.0