Logging errors to a database

#1
[eluser]jonez[/eluser]
Hi I'm trying to log PHP error's and 404's to a database. I've tried to overload CI_Log's write_log and CI_Exceptions show_error, but in both cases the main CI object hasn't been created so I can't use DB methods.

I tried wrapping get_instance in a try/catch, but it still fails. I'm assuming the error handlers are setup this way to catch errors in core files.

Does anyone have a clever solution? I'm not opposed to using a library over a core extension as long as it doesn't require custom error handling in methods. Ideally I'd like errors to propagate as they do now and simply add logging to a database.

Thanks!

#2
[eluser]jonez[/eluser]
My initial solution for logging PHP errors to a database using CI3-dev:

db.error
Code:
CREATE TABLE `error` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(255) NOT NULL,
  `message` text NOT NULL,
  `file_path` varchar(255) NOT NULL,
  `line_number` varchar(255) NOT NULL,
  `ip_address` varchar(255) NOT NULL,
  `created_datetime` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

/application/config/hooks.php
Code:
$hook['post_controller_constructor'][] = array(
'function' => 'check_db',
'filename' => 'log.php',
'filepath' => 'hooks',
);

/application/hooks/log.php
Code:
<?php

function check_db( ) {
$ci =& get_instance( );
$ci->log->to_database( true );
}

?>

/application/core/MY_Log.php
Code:
<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class MY_Log extends CI_Log {
protected $_log_db;

public function to_database( $status = false ) {
  $this->_log_db = $status;
}

public function write_log( $level, $msg ) {
  parent::write_log( $level, $msg );

  $level = strtoupper( $level );
  if ( ( !isset( $this->_levels[ $level ] ) || ( $this->_levels[ $level ] > $this->_threshold ) ) && !isset( $this->_threshold_array[ $this->_levels[ $level ] ] ) ) {
   return false;
  }

  if ( $this->_log_db == true ) {
   $ci =& get_instance( );
   $ci->load->database( );

   $s = array( 'Severity: ', 'Notice  -->', 'Warning  -->', 'Error  -->' );
   $r = array( '', '', '', '' );
   $msg = trim( str_replace( $s, $r, $msg ) );

   $line = trim( substr( $msg, strrpos( $msg, ' ' ) ) );

   $re = preg_match( '/\/[^ ]+/', $msg, $path );
   $path = $path[ 0 ];

   $msg = trim( substr( $msg, 0, strpos( $msg, '/' ) ) );

   $data = array(
    'code' => 500,
    'message' => $msg,
    'file_path' => $path,
    'line_number' => $line,
    'ip_address' => $_SERVER[ 'REMOTE_ADDR' ],
    'created_datetime' => date( 'Y-m-d H:i:s' ),
   );

   $ci->db->insert( 'error', $data );
  }
}
}

?>


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.