Monitor your server in WordPress dashboard

Monitor your server in WordPress dashboard

WordPress dashboard API allow you to do many useful things using dashboard widgets. I recently came across this very useful code: a dashboard widget that allows you to monitor your server directly on WordPress’ dashboard.

Paste the code in your functions.php file, and you’re done.

function slt_PHPErrorsWidget() {

$logfile = ‘/home/path/logs/php-errors.log’; // Enter the server path to your logs file here

$displayErrorsLimit = 100; // The maximum number of errors to display in the widget

$errorLengthLimit = 300; // The maximum number of characters to display for each error

$fileCleared = false;

$userCanClearLog = current_user_can( ‘manage_options’ );

// Clear file?

if ( $userCanClearLog && isset( $_GET[“slt-php-errors”] ) && $_GET[“slt-php-errors”]==”clear” ) {

$handle = fopen( $logfile, “w” );

fclose( $handle );

$fileCleared = true;

}

// Read file

if ( file_exists( $logfile ) ) {

$errors = file( $logfile );

$errors = array_reverse( $errors );

if ( $fileCleared ) echo ‘

File cleared.

‘;

if ( $errors ) {

echo ‘

‘.count( $errors ).’ error’;

if ( $errors != 1 ) echo ‘s’;

echo ‘.’;

if ( $userCanClearLog ) echo ‘ [ CLEAR LOG FILE ]’;

echo ‘

‘;

echo ‘

‘; echo ‘

‘; $i = 0; foreach ( $errors as $error ) { echo ‘ 


  ‘; $errorOutput = preg_replace( ‘/[([^]]+)]/’, ‘[$1]‘, $error, 1 ); if ( strlen( $errorOutput ) > $errorLengthLimit ) { echo substr( $errorOutput, 0, $errorLengthLimit ).’ […]’; } else { echo $errorOutput; } echo ‘


  ‘; $i++; if ( $i > $displayErrorsLimit ) { echo ‘



  More than ‘.$displayErrorsLimit.’ errors in log…


  ‘; break; } } echo ‘  
  
  
    ‘; } else { echo ‘
  
  
  
    No errors currently logged.
  
  
  
    ‘; } } else { echo ‘
  
  
  
    There was a problem reading the error log file.
  
  
  
    ‘; } }
  
  
  
    // Add widgets function slt_dashboardWidgets() { wp_add_dashboard_widget( ‘slt-php-errors’, ‘PHP errors’, ‘slt_PHPErrorsWidget’ ); } add_action( ‘wp_dashboard_setup’, ‘slt_dashboardWidgets’ );