Skip to main content
Code Tutorial

Logging PHP errors with TypeRocket

To log PHP errors with TypeRocket add the following code to your wp-config.php file. If you are using TypeRocket Pro errors will be logged based on your config/logging.php settings. If you are using TypeRocket Open or TypeRocket has not be loaded before an errors occures a fallback log file will be used.

define('TYPEROCKET_LOG_FILE_FOLDER', __DIR__ . '/logs');

function typerocket_log_errors($error = null, $errstr = null, $errfile = null, $errline = null) {
    // No error, just skip the error handling code.
    $last_error = error_get_last();

    if($error instanceof \Throwable) {
        $error = ['code' => $error->getCode(), 'message' => $error->getMessage(), 'line' => $error->getLine(), 'file' => $error->getFile()];
    }
    elseif($errstr) {
        $error = ['code' => $error, 'message' => $errstr, 'line' => $errline, 'file' => $errfile];
    }
    elseif (!$last_error && is_null($error)) {
        return null;
    }

    $message = json_encode($error ?? $last_error);

    if(class_exists('TypeRocketPro\Utility\Log')) {
        \TypeRocketPro\Utility\Log::error($message);
    } else {
        $folder = TYPEROCKET_LOG_FILE_FOLDER;
        if(!file_exists($folder)) {
            mkdir($folder, 0777, true);
        }

        $env = 'typerocket';
        if(function_exists('wp_get_environment_type')) {
            $env = wp_get_environment_type();
        }

        $time = date('Y-m-d H:i:s', time());
        $message = "[{$time}] {$env}.ERROR {$message}"  . PHP_EOL;

        file_put_contents("{$folder}/typerocket-fallback.log",$message, FILE_APPEND);
    }

    return null;
}

set_error_handler('typerocket_log_errors');
set_exception_handler('typerocket_log_errors');
register_shutdown_function('typerocket_log_errors');

IMPORTANT: Ensure your web server does not allow .log files to be accessed from the web.

Access More TypeRocket

Join our community mailing list and get notified before anyone else. Get videos and more.

By using our website you agree to our Cookie policy.