Logs are very helpful for troubleshooting and debugging issues on your WordPress sites. At Kinsta, you can access three types of logs: error logs, kinsta-cache-perf (cache performance) logs, and access logs.

Accessing logs through the MyKinsta dashboard is straightforward: navigate to WordPress Sites, select the desired site, and click the Logs tab to open the Log viewer page.

Now, with the introduction of the Kinsta API, you can programmatically access these logs. As an agency, you can create custom interfaces for accessing logs, while larger teams can leverage tools like Slack to create a custom Slackbot. This bot can interact with the API through Slash commands, streamlining log retrieval and management.

This guide delves into the logs endpoint available through the API, its potential uses, and how to seamlessly access these logs within a Slack environment.

Understanding the Kinsta API

The Kinsta API is a powerful tool that allows you to interact with Kinsta services like hosted WordPress sites programmatically. It can help automate various tasks related to WordPress management, including site creation, retrieving site information, getting the status of a site, browsing and restoring backups, fetching site logs, and more.

To use Kinsta’s API, you must have an account with at least one WordPress site, application, or database in MyKinsta. You also need to generate an API key to authenticate and access your account.

To generate an API key:

  1. Go to your MyKinsta dashboard.
  2. Navigate to the API Keys page (Your name > Company settings > API Keys).
  3. Click Create API Key.
  4. Choose an expiration or set a custom start date and number of hours for the key to expire.
  5. Give the key a unique name.
  6. Click Generate.

After creating an API key, copy it and store it somewhere safe (using a password manager is recommended), as this is the only time it is revealed within MyKinsta. You can generate multiple API keys, which will be listed on the API Keys page. If you need to revoke an API key, click the Revoke button next to its name and expiry date.

Accessing Server Logs With Kinsta API

To access logs with the Kinsta API, you need to specify the site environment ID, the type of log you wish to fetch (e.g. error, access, or kinsta-cache-perf), and the number of log lines to retrieve.

Let’s explore this endpoint and later integrate it into a Slackbot so you can use Slack’s Slash commands to interact with the Kinsta API.

You can obtain your site’s environment ID programmatically through the get site environment endpoint, which returns details about your site’s environment, including its ID:

{
  "site": {
    "environments": [
      {
        "id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
        "name": "first-site",
        "display_name": "First site",
        "is_blocked": false,
        "id_edge_cache": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
        "cdn_cache_id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
        "is_premium": false,
        "domains": [
          {
            "id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
            "name": "example.com",
            "type": "live"
          }
        ],
        "primaryDomain": {
          "id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
          "name": "example.com",
          "type": "live"
        },
        "ssh_connection": {
          "ssh_port": "808080",
          "ssh_ip": {
            "external_ip": "1xx.1xx.1xx.1xx"
          }
        },
        "container_info": {
          "id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
          "php_engine_version": "php8.0"
        }
      }
    ]
  }
}

Once you have your site’s environment ID, you can then send a GET request to /sites/environments/{env_id}/logs?file_name=error&lines=100:

curl -i -X GET \
  'https://api.kinsta.com/v2/sites/environments/{env_id}/logs?file_name=access&lines=100' \
  -H 'Authorization: Bearer '

This will return a String with the specified number of log lines:

{
    "environment": {
        "container_info": {
            "logs": "mysite.kinsta.cloud ::1 [07/Dec/2023:00:02:01 +0000] HEAD \"/wp-cron.php?server_triggered_cronjob\" HTTP/2.0 200 \"-\" \"curl/7.68.0\" - \"/wp-cron.php\" - - 230 0.017 0.018\nmysite.kinsta.cloud ::1 [07/Dec/2023:00:17:01 +0000] HEAD \"/wp-cron.php?server_triggered_cronjob\" HTTP/2.0 200 \"-\" \"curl/7.68.0\" - \"/wp-cron.php\" - - 230 0.139 0.139\nmysite.kinsta.cloud ::1 [07/Dec/2023:00:32:01 +0000] HEAD \"/wp-cron.php?server_triggered_cronjob\" HTTP/2.0 200 \"-\" \"curl/7.68.0\" - \"/wp-cron.php\" - - 230 0.016 0.016\nmysite.kinsta.cloud ::1 [07/Dec/2023:00:47:01 +0000] HEAD \"/wp-cron.php?server_triggered_cronjob\" HTTP/2.0 200 \"-\" \"curl/7.68.0\" - \"/wp-cron.php\" - - 230 0.015 0.015\n"
        }
    }
}

You can then format the output to separate each line with the n line break. For example, with JavaScript, you can use the split() method:

const logsData = {
    "environment": {
        "container_info": {
            "logs": "string"
        }
    }
};

const logsString = logsData.environment.container_info.logs;

// Splitting the logs string into an array of log entries based on the newline character '\n'
const logEntries = logsString.split('\n');

console.log(logEntries);

Implementing Slack Slash Commands for Retrieving Server Logs With Kinsta API

In a recent guide, the process of crafting a Slackbot using Node.js and the Kinsta API for site management was explained. The guide outlined creating a Slackbot and establishing interaction with the Kinsta API via a Node.js application hosted on our Application Hosting platform.

For this guide, let’s create a new Slack Slash command to get your site’s log endpoints. To follow along here, first review the guide above to understand the Node.js application and how to configure your personalized Slackbot.

Once completed, you can proceed to clone our starter project with Git:

  1. Navigate to your preferred directory for storing your code and execute the following command in your terminal:
    git clone -b tutorial-1 --single-branch https://github.com/olawanlejoel/SlackBot-KinstaAPI.git
  2. Move into the project folder and install all the required dependencies:
    cd SlackBot-KinstaAPI
    npm install

Creating Slash Commands on Slack for Retrieving Server Logs

In the previous Kinsta API Slackbot guide, five slash commands were created to handle the following:

  • /site_id [site name]: Used to retrieve site ID.
  • /environment_id [site name]: Used to retrieve environment ID.
  • /clear_site_cache [environment id]: Used to clear site cache.
  • /restart_php_engine [environment id]: Used to a site’s restart PHP engine.
  • /operation_status [operation id]: Used to check an operation’s status.

For this guide, you create a new command. To set up Slash Commands on Slack for retrieving server logs, follow these steps:

  1. Open your Slack application and go to the Slash Commands menu on the left sidebar.
  2. Click the Create New Command button.
  3. Enter the details as follows:
    • Command: /get_site_logs
    • Short Description: Retrieve your site’s log files, including error.log, kinsta-cache-perf.log, and access.log.
    • Usage Hint: [Environment ID] [File name] [Lines, e.g., 1000]

By using this command along with parameters like [Environment ID], [File name], and [Lines], users can request specific log files, ensuring they access the necessary information. Additionally, we configured the command to have default values in case the user doesn’t input the log file name and line count, ensuring a smoother experience.

Implementing Node.js Fetch Requests for Server Logs Operations

Once you’ve created the slash command, you can modify your Node.js app to respond to the command. Begin by creating an asynchronous function to interact with the endpoint.

In the app.js file, define a getSiteLogs() function that receives three parameters from Slack:

async function getSiteLogs(environmentId, fileName, lines) {
    const query = new URLSearchParams({
        file_name: fileName || 'error',
        lines: lines || 1000,
    }).toString();
    const resp = await fetch(
        `https://api.kinsta.com/v2/sites/environments/${environmentId}/logs?${query}`,
        {
            method: 'GET',
            headers: getHeaders,
        }
    );
    const data = await resp.json();
    return data;
}

The function communicates with the Kinsta API using JavaScript’s Fetch API. The parameters are expected inputs, which are meant to be received from Slack commands and then passed on to these functions for execution.

In the code, you will notice that the query parameters have some default values, assuming the file name and log lines are not added via Slack.

With the getSiteLogs() function in place, the next step involves configuring the Slack commands. This configuration entails receiving input values from Slack, invoking the function, and sending a specific response back to Slack.

Configuring Slash Commands With Node.js for Retrieving Server Logs

To configure a Slash command, you use the app.command() function, which functions similarly to event listeners in JavaScript. You specify the command you wish to listen for and then create an asynchronous callback function to define the desired action. This function takes three parameters:

  • command: Contains the details of the slash command sent by the user.
  • ack: Acknowledges the receipt of the slash command.
  • say: Sends a message back to the Slack channel.

Here is the configuration for the /get_site_logs command:

app.command('/get_site_logs', async ({ command, ack, say }) => {
    await ack();

    const [environmentId, fileName, lines] = command.text.split(' ');
    let response = await getSiteLogs(environmentId, fileName, lines);

    if (response) {
        const logs = response.environment.container_info.logs.split('\n');
        const formattedLogs = logs.join('\n\n'); // or any other formatting needed
        say(`Hey 👋, \n\nHere are the logs for ${fileName}:\n\n${formattedLogs}`);
    } else {
        say(`Sorry, no logs found for ${fileName}.`);
    }
});

The code above uses the getSiteLogs() function to fetch logs based on the parameters. If logs are retrieved successfully, it formats them and sends a Slack message displaying the logs for the specified file using the say() function. If no logs are found, it notifies the user accordingly.

You can deploy the Node.js server code to Kinsta to make your Slackbot live.

Demo of interacting with the server logs endpoint with Slack Slash command and Kinsta API

You can access the complete code for this project on our GitHub repository.

Summary

In this guide, you learned how to use the Kinsta API logs endpoints effectively. This endpoint empowers you to retrieve your site’s server logs seamlessly for faster troubleshooting.

The Kinsta API offers many capabilities beyond this, so you are encouraged to explore additional endpoints and brainstorm innovative ways to leverage them in your projects.

How do you currently leverage the Kinsta API? Are there any specific features you’d love to see introduced or made accessible in the future?

Joel Olawanle Kinsta

Joel is a Frontend developer working at Kinsta as a Technical Editor. He is a passionate teacher with love for open source and has written over 200 technical articles majorly around JavaScript and it's frameworks.