PageRenderTime 132ms CodeModel.GetById 92ms app.highlight 32ms RepoModel.GetById 1ms app.codeStats 1ms

/openbiz/bin/service/logService.php

https://github.com/asipto/siremis
PHP | 406 lines | 241 code | 24 blank | 141 comment | 24 complexity | d4a58e28462fc0b51138772155bf3610 MD5 | raw file
  1<?php
  2/**
  3 * PHPOpenBiz Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 *
 10 * @package   openbiz.bin.service
 11 * @copyright Copyright &copy; 2005-2009, Rocky Swen
 12 * @license   http://www.opensource.org/licenses/bsd-license.php
 13 * @link      http://www.phpopenbiz.org/
 14 * @version   $Id$
 15 */
 16
 17require_once 'Zend/Log.php';
 18require_once 'Zend/Log/Writer/Stream.php';
 19
 20/**
 21 * ioService class is the plug-in service of handling file import/export
 22 *
 23 * @package   openbiz.bin.service
 24 * @author    Rocky Swen
 25 * @copyright Copyright (c) 2003-2009, Rocky Swen
 26 * @access    public
 27 */
 28class logService extends MetaObject
 29{
 30    /**
 31     * Log Levels are the highest level of logging to record.
 32     * By default, will log all entries up to the selected level
 33     * If this is set to NULL, logging is disabled
 34
 35     * EMERG   = 0;  // Emergency: system is unusable
 36     * ALERT   = 1;  // Alert: action must be taken immediately
 37     * CRIT    = 2;  // Critical: critical conditions
 38     * ERR     = 3;  // Error: error conditions
 39     * WARN    = 4;  // Warning: warning conditions
 40     * NOTICE  = 5;  // Notice: normal but significant condition
 41     * INFO    = 6;  // Informational: informational messages
 42     * DEBUG   = 7;  // Debug: debug messages
 43     *
 44     * @var int
 45     */
 46    private $_level;
 47
 48    /**
 49     * Logging format options include CSV, XML and HTML
 50     *
 51     * @var string
 52     */
 53    private $_format;
 54    
 55    /**
 56     * Organize files by in different ways:
 57     * PROFILE - pased on a profile userID
 58     * LEVEL - Store log files groups by their level
 59     * DATE - write log entries into a different file for each day
 60     *
 61     * @var string
 62     */
 63    private $_org;
 64    /**
 65     * Holds the formatter for a log object.  This object dictates how a log file is logged.
 66     *
 67     * @var object
 68     */
 69    private $_formatter;
 70    /**
 71     * Holds the file extension set based on the preferred format
 72     *
 73     * @var string
 74     */
 75    private $_extension = '.csv';
 76
 77    /**
 78     * Initialize logService with xml array metadata
 79     *
 80     * @param array $xmlArr
 81     * @return void
 82     */
 83    public function __construct(&$xmlArr)
 84    {
 85        $this->readMetadata($xmlArr);
 86        //Check that logging is enabled
 87        if (is_int($this->_level) == FALSE)
 88            return;
 89        $this->setFormatter();
 90        $this->setExtension();
 91    }
 92
 93    /**
 94     * Read array meta data, and store to meta object
 95     *
 96     * @param array $xmlArr
 97     * @return void
 98     */
 99    protected function readMetadata(&$xmlArr)
100    {
101        parent::readMetaData($xmlArr);
102        $level = strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["LEVEL"]);
103        $this->_level = (int) $level;
104        $this->_format = strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["FORMAT"]);
105        $this->_org = strtoupper($xmlArr["PLUGINSERVICE"]["LOG_CONFIG"]["ATTRIBUTES"]["ORG"]);
106    }
107
108    /**
109     * The primary log function that will take an incoming message and specified paramter and log in the
110     * appropriate location and format
111     *
112     * @param int $level - Follow common BSD error levels
113     * @param string $package - A way to group log messages
114     * @param string $message - The actual message to log
115     * @return boolean -TRUE on success otherwise FALSE
116     */
117    public function log($priority, $package, $message)
118    {
119        if (DEBUG == 0 && $priority == LOG_DEBUG)
120        	return true;
121    	//Adapt PHP LOG priority
122        switch ($priority)
123        {
124            case LOG_EMERG : // 	system is unusable
125            case LOG_ALERT :	// action must be taken immediately
126            case LOG_CRIT :	// critical conditions
127                $level = 2;
128                break;
129            case LOG_ERR :	// error conditions
130                $level = 3;
131                break;
132            case LOG_WARNING : // warning conditions
133                $level = 4;
134                break;
135            case LOG_NOTICE : //	normal, but significant, condition
136            case LOG_INFO :	// informational message
137            case LOG_DEBUG :	// debug-level message
138                $level = 7;
139                break;
140        }
141        //echo "log levels: ".LOG_EMERG.", ".LOG_ALERT.", ".LOG_CRIT.", ".LOG_ERR.", ".LOG_WARNING.", ".LOG_NOTICE.", ".LOG_INFO.", ".LOG_DEBUG."<br>";
142
143        if ($this->_level == FALSE)
144            return true;
145        //Get the file path
146        $this->_level = $level;
147        $path = $this->_getPath($file_name);
148        $this->prepFile($path);
149        //Create the log writer object
150        $writer = new Zend_Log_Writer_Stream($path);
151        $writer->setFormatter($this->_formatter);
152        //Instantiate logging object
153        $logger = new Zend_Log($writer);
154        //Filter log entries to those allowed by configuration
155        $filter = new Zend_Log_Filter_Priority($this->_level);
156        $logger->addFilter($filter);
157
158        $logger->setEventItem('back_trace', 'n/a');
159        $logger->setEventItem('package', $package);
160        $logger->setEventItem('date', date("m/d/Y"));
161        $logger->setEventItem('time', date("H:i:s"));
162
163        //Write Log Entry
164        $logger->log($message, $level);
165        $this->closeFile($path);
166        return TRUE;
167    }
168
169    /**
170     * The primary log function that will take an incoming message and specified paramter and log in the
171     * appropriate location and format
172     *
173     * @param int $level - Follow common BSD error levels
174     * @param string $package - A way to group log messages
175     * @param string $message - The actual message to log
176     * @param string $fileName - An optional specific file name where the message should be logged
177     * @param string $string - An optional list of the Application stack at the time of error
178     * @return boolean -TRUE on success otherwise FALSE
179     */
180    public function logError($level = 7, $package, $message, $fileName = NULL, $backTrace = '')
181    {
182        //Adapt PHP Errors
183        switch ($level)
184        {
185            case 8:          // E_NOTICE
186            case 1024:       // E_USER_NOTICE
187                $level = 4;
188                break;
189
190            case 2048:       //E_STRICT
191            case 8192:       //E_DEPRICIATED
192            case 16384:      //E_DEPRICIATED
193                $level = 5;
194                break;
195
196            case 2:          //E_WARNING
197            case 512:        //E_USER_WARNING
198                $level = 3;
199                break;
200
201            case 256:
202                $level = 2;
203                break;
204            
205            default:
206                $level = 2;
207        }
208
209        if ($this->_level == FALSE)
210            return true;
211        //Get the file path
212        $this->_level = $level;
213        $path = $this->_getPath($fileName);
214        $this->prepFile($path);
215
216        //Create the log writer object
217        $writer = new Zend_Log_Writer_Stream($path);
218        $writer->setFormatter($this->_formatter);
219
220        //Instantiate logging object
221        $logger = new Zend_Log($writer);
222
223        //Filter log entries to those allowed by configuration
224        $filter = new Zend_Log_Filter_Priority($this->_level);
225        $logger->addFilter($filter);
226        //Set additional information about the class and function that called the log
227
228
229        // Add custom elements to default log package
230        $logger->setEventItem('back_trace', $backTrace);
231        $logger->setEventItem('package', $package);
232        $logger->setEventItem('date', date("m/d/Y"));
233        $logger->setEventItem('time', date("H:i:s"));
234        //Write Log Entry
235        $logger->log($message, $level);
236        $this->closeFile($path);
237        return TRUE;
238    }
239
240    /**
241     * Set the formatter based on the type of format selected in app.inc
242     *
243     * @return void
244     */
245    public function setFormatter()
246    {
247        switch ($this->_format)
248        {
249            case 'HTML':
250            //HTML Format
251                $this->_formatter = new Zend_Log_Formatter_Simple('<tr><td>%date%</td> <td>%time%</td> <td>%priorityName%</td> <td>%package%</td> <td>%message%</td> <td>%back_trace%</td> </tr>' . PHP_EOL);
252                break;
253            case 'XML':
254            //XML Format
255                require_once 'Zend/Log/Formatter/Xml.php';
256                $this->_formatter = new Zend_Log_Formatter_Xml();
257                break;
258            case 'CSV':
259            default:
260            //CSV Format
261                $this->_formatter = new Zend_Log_Formatter_Simple("'%date%','%time%','%priorityName%','%package%','%message%','%back_trace%'" . PHP_EOL);
262                break;
263        }
264    }
265    /**
266     * Set the extension based on the type of format selected in app.inc
267     *
268     * @return void
269     */
270    public function setExtension()
271    {
272        switch ($this->_format)
273        {
274            case 'HTML':
275                $this->_extension = '.html';
276                break;
277            case 'XML':
278                $this->_extension = '.xml';
279                break;
280            case 'CSV':
281            default:
282                $this->_extension = '.log';
283                break;
284        }
285    }
286    /**
287     * Either open a new file with the correct string or remove a previous closing string
288     *
289     * @return void
290     */
291    public function prepFile($path)
292    {
293        //Check for existing file and HTML format
294        if (file_exists($path) and $this->_format == 'HTML')
295        {
296            $file = file($path);
297            array_pop($file);
298            file_put_contents($path, $file);
299        } elseif ($this->_format == 'HTML')
300        {
301            $html = '<html><head></head><body><table border="1">' . PHP_EOL;
302            $file = fopen($path, 'a');
303            fwrite($file, $html);
304            fclose($file);
305        } elseif (file_exists($path) and $this->_format == 'XML')
306        {
307            $file = file($path);
308            array_pop($file);
309            file_put_contents($path, $file);
310        } elseif ($this->_format == 'XML')
311        {
312            $xml = '<?xml version="1.0" standalone="no"?><log>' . PHP_EOL;
313            $file = fopen($path, 'a');
314            fwrite($file, $xml);
315            fclose($file);
316        }
317    }
318
319    /**
320     * Close a file with the correct string depending on the configured format
321     *
322     * @return void
323     */
324    public function closeFile($path)
325    {
326        //Close up the file if needed
327        switch ($this->_format)
328        {
329            case 'HTML':
330                $html = "</table></body></html>";
331                $file = fopen($path, 'a');
332                fwrite($file, $html);
333                fclose($file);
334                break;
335            case 'XML':
336                $xml = "</log>";
337                $file = fopen($path, 'a');
338                fwrite($file, $xml);
339                fclose($file);
340                break;
341            default:
342                break;
343        }
344    }
345
346    /**
347     * Get path based on config options
348     *
349     * @global BizSystem $g_BizSystem
350     * @param string $fileName
351     * @return string log_path - The path where a log entry should be written
352     */
353    private function _getPath($fileName = null)
354    {
355        if ($fileName)
356            return LOG_PATH . '/' . $fileName . $this->_extension;
357        switch ($this->_org)
358        {
359            case 'DATE':
360                return LOG_PATH . '/' . date("Y_d_m") . $this->_extension;
361                break;
362            case 'LEVEL':
363                switch ($this->_level)
364                {
365                    case 0:
366                        $level = 'EMERG';
367                        break;
368                    case 1:
369                        $level = 'ALERT';
370                        break;
371                    case 2:
372                        $level = 'CRIT';
373                        break;
374                    case 3:
375                        $level = 'ERR';
376                        break;
377                    case 4:
378                        $level = 'WARN';
379                        break;
380                    case 5:
381                        $level = 'NOTICE';
382                        break;
383                    case 6:
384                        $level = 'INFO';
385                        break;
386                    case 7:
387                        $level = 'DEBUG';
388                        break;
389                    default:
390                        ;
391                        break;
392                }
393                return LOG_PATH . '/' . $level . $this->_extension;
394                break;
395            case 'PROFILE':
396                $profile = BizSystem::getUserProfile('USERID');
397                if (! $profile)
398                    $profile = 'Guest';
399                return LOG_PATH . '/' . $profile . $this->_extension;
400                break;
401            default:
402                ;
403                break;
404        }
405    }
406}