Obtenir les messages de journal pour une exécution de transfert

Récupère tous les messages de journal produits lors d'une exécution de transfert spécifique du service de transfert de données BigQuery.

Exemple de code

Java

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Java.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;
import com.google.cloud.bigquery.datatransfer.v1.RunName;
import com.google.cloud.bigquery.datatransfer.v1.TransferMessage;
import java.io.IOException;

public class ListTransferLogs {

  /**
   * Prints the transfer logs for a given transfer run.
   *
   * @param projectId The Google Cloud project ID (for example, "example-project-id").
   * @param location The geographic location of the transfer configuration (for example,
   *     "us-central1").
   * @param transferConfigId The ID of the transfer configuration (for example,
   *     "1234a-5678-90b1-2c3d-4e5f67890g12").
   * @param runId The ID of the transfer run (for example, "6789b-0123-45c6-7d8e-9f0a12345b67").
   */
  public static void listTransferLogs(
      String projectId, String location, String transferConfigId, String runId) {
    RunName parent =
        RunName.ofProjectLocationTransferConfigRunName(
            projectId, location, transferConfigId, runId);

    try (DataTransferServiceClient client = DataTransferServiceClient.create()) {
      System.out.printf("Logs for transfer run %s:%n", runId);
      for (TransferMessage log : client.listTransferLogs(parent).iterateAll()) {
        System.out.printf("  - %s: %s%n", log.getSeverity(), log.getMessageText());
      }
    } catch (NotFoundException err) {
      System.err.printf(
          "error: transfer run '%s' not found in project '%s' location '%s': %s%n",
          runId, projectId, location, err.getMessage());
    } catch (ApiException | IOException err) {
      System.err.printf(
          "error: failed to list transfer logs for '%s': %s%n", parent, err.getMessage());
    }
  }

Node.js

Avant d'essayer cet exemple, suivez les instructions de configuration pour Node.js du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Node.js.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.

const {
  DataTransferServiceClient,
} = require('@google-cloud/bigquery-data-transfer');
const {status} = require('@grpc/grpc-js');

const client = new DataTransferServiceClient();

/**
 * Lists log messages for a transfer run.
 * Transfer runs are created for each transfer configuration, and they may have associated log messages.
 *
 * @param {string} projectId Google Cloud project ID (for example, 'example-project-id').
 * @param {string} location The geographic location of the transfer configuration (for example, 'us-central1').
 * @param {string} transferConfigId The transfer configuration ID (for example, '1234a-5678-9b12c').
 * @param {string} runId The transfer run ID (for example, 'd123e-4567-89b0c-1d23e').
 */
async function listTransferLogs(projectId, location, transferConfigId, runId) {
  const parent = client.projectLocationTransferConfigRunPath(
    projectId,
    location,
    transferConfigId,
    runId,
  );
  const request = {
    parent,
  };

  try {
    const [logs] = await client.listTransferLogs(request);

    if (logs.length === 0) {
      console.error(`No transfer logs found for ${parent}.`);
      return;
    }

    console.log(`Found ${logs.length} transfer log entries:`);
    for (const log of logs) {
      console.log(
        `  [${log.severity}] ${new Date(
          log.messageTime.seconds * 1000,
        ).toISOString()}: ${log.messageText}`,
      );
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Transfer run not found: ${runId}`);
    } else {
      console.error('Error listing transfer logs:', err);
    }
  }
}

Python

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Python.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.


import google.api_core.exceptions
from google.cloud import bigquery_datatransfer_v1

client = bigquery_datatransfer_v1.DataTransferServiceClient()


def list_transfer_logs(
    project_id: str, location: str, transfer_config_id: str, run_id: str
) -> None:
    """Prints the transfer logs for a given transfer run.

    This sample shows how to retrieve the logs for a specific transfer run,
    which can be useful for debugging and monitoring transfer jobs.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the transfer configuration (e.g., 'us-central1').
        transfer_config_id: The ID of the transfer configuration.
        run_id: The ID of the transfer run.
    """

    parent = client.run_path(
        f"{project_id}/locations/{location}", transfer_config_id, run_id
    )

    try:
        pager = client.list_transfer_logs(parent=parent)

        print(f"Logs for transfer run {run_id}:")
        for log in pager:
            print(f"  - {log.severity.name}: {log.message_text}")

    except google.api_core.exceptions.NotFound:
        print(
            f"Error: Transfer run '{run_id}' not found in project '{project_id}' location '{location}'."
        )

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud , consultez l'explorateur d'exemplesGoogle Cloud .