Monitoring PHP OPcache with Telegraf, InfluxDB, and Grafana

The PHP OPcache extension is a powerful tool that can significantly improve the performance of your PHP applications by storing precompiled script bytecode in shared memory. However, like any caching system, it’s crucial to monitor the performance and usage of your OPcache to ensure that it’s configured correctly and operating optimally. In this post, we will outline a method to monitor OPcache using a combination of Telegraf, InfluxDB, and Grafana.


For this tutorial, we assume that you have the following:

  • A PHP environment with OPcache enabled
  • An InfluxDB instance up and running
  • A Grafana instance up and running
  • Telegraf installed and running on the server where PHP is installed

Step 1: Create a PHP Script to Expose OPcache Stats

First, let’s create a PHP script that will expose the OPcache stats in a JSON format that can be consumed by Telegraf. Save the following script as opcache.php:

header('Content-Type: application/json');
$status = opcache_get_status();
if ($status) {
    unset($status['scripts']); // Remove 'scripts' element
    echo json_encode($status);
} else {
    echo json_encode(['error' => 'OPCache not enabled']);

This script fetches the OPcache status, removes the scripts element, and then outputs the remaining data as a JSON object.

Step 2: Configure Telegraf to Collect the OPcache Stats

Next, we need to configure Telegraf to collect the OPcache stats from our PHP script using the inputs.http plugin. Edit your Telegraf configuration file (usually located at /etc/telegraf/telegraf.conf or /etc/telegraf/telegraf.d/your-config.conf) and add the following:

  urls = ["https://localhost/opcache.php"]
  data_format = "json"

This configuration tells Telegraf to make an HTTP request to https://localhost/opcache.php and interpret the response as JSON. Make sure to replace https://localhost/opcache.php with the actual URL of your opcache.php script.

Step 3: Visualize the Data in Grafana

Finally, we can visualize our OPcache stats in Grafana:

  1. In Grafana, add a new data source for your InfluxDB instance (if you haven’t done so already).
  2. Create a new dashboard.
  3. Add panels to your dashboard and select your InfluxDB data source.
  4. Now, you can create queries to visualize the OPcache data collected by Telegraf. For example, you might want to visualize opcache_statistics.hits, opcache_statistics.misses, or any other stats exposed by the opcache_get_status() function.

And that’s it! You’re now monitoring OPcache with Telegraf, InfluxDB, and Grafana. This setup will give you a continuous stream of data about your OPcache performance, and you can build Grafana dashboards to visualize and analyze this data in real time. Happy monitoring!

Scroll to Top