Enumera mensajes de trabajos

Demuestra cómo solicitar una lista de mensajes de trabajos.

Muestra de código

C#

Para autenticarte en Dataflow, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

using Google.Api.Gax;
using Google.Cloud.Dataflow.V1Beta3;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedMessagesV1Beta3ClientSnippets
{
    /// <summary>Snippet for ListJobMessages</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void ListJobMessagesRequestObject()
    {
        // Create client
        MessagesV1Beta3Client messagesV1Beta3Client = MessagesV1Beta3Client.Create();
        // Initialize request argument(s)
        ListJobMessagesRequest request = new ListJobMessagesRequest
        {
            ProjectId = "",
            JobId = "",
            MinimumImportance = JobMessageImportance.Unknown,
            StartTime = new Timestamp(),
            EndTime = new Timestamp(),
            Location = "",
        };
        // Make the request
        PagedEnumerable<ListJobMessagesResponse, JobMessage> response = messagesV1Beta3Client.ListJobMessages(request);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (JobMessage item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (ListJobMessagesResponse page in response.AsRawResponses())
        {
            // Do something with each page of items
            Console.WriteLine("A page of results:");
            foreach (JobMessage item in page)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<JobMessage> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
        foreach (JobMessage item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

Go

Para autenticarte en Dataflow, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import (
	"context"
	"fmt"
	"io"

	dataflow "cloud.google.com/go/dataflow/apiv1beta3"
	dataflowpb "cloud.google.com/go/dataflow/apiv1beta3/dataflowpb"
	"google.golang.org/api/iterator"
)

// listJobMessages retrieves and prints messages for a Dataflow job.
func listJobMessages(ctx context.Context, w io.Writer, projectID string, locationID string, jobID string) error {
	client, err := dataflow.NewMessagesV1Beta3Client(ctx)
	if err != nil {
		return fmt.Errorf("NewMessagesV1Beta3Client failed: %w", err)
	}
	defer client.Close()

	req := &dataflowpb.ListJobMessagesRequest{
		ProjectId: projectID,
		Location:  locationID,
		JobId:     jobID,
	}

	it := client.ListJobMessages(ctx, req)
	for {
		msg, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("failed to iterate job messages: %w", err)
		}
		fmt.Fprintf(w, "Message ID: %s, Importance: %s, Text: %s\n", msg.GetId(), msg.GetMessageImportance(), msg.GetMessageText())
	}

	return nil
}

Java

Para autenticarte en Dataflow, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.dataflow.v1beta3.JobMessage;
import com.google.dataflow.v1beta3.ListJobMessagesRequest;
import com.google.dataflow.v1beta3.MessagesV1Beta3Client;
import java.io.IOException;

public class ListJobMessages {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "us-central1";
    String jobId = "example-job-id";
    listJobMessages(projectId, locationId, jobId);
  }

  public static void listJobMessages(String projectId, String locationId, String jobId)
      throws IOException {
    // Initializes client using Application Default Credentials for authentication.
    try (MessagesV1Beta3Client client = MessagesV1Beta3Client.create()) {
      ListJobMessagesRequest request =
          ListJobMessagesRequest.newBuilder()
              .setProjectId(projectId)
              .setLocation(locationId)
              .setJobId(jobId)
              .build();

      for (JobMessage message : client.listJobMessages(request).iterateAll()) {
        System.out.printf("Message ID: %s%n", message.getId());
        System.out.printf("Importance: %s%n", message.getMessageImportance());
        System.out.printf("Text: %s%n", message.getMessageText());
      }
    }
  }
}

Node.js

Para autenticarte en Dataflow, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

'use strict';

const {MessagesV1Beta3Client} = require('@google-cloud/dataflow');
const {status} = require('@grpc/grpc-js');

const client = new MessagesV1Beta3Client();

/**
 * Lists messages associated with a Dataflow job.
 *
 * @param {string} projectId - The ID of the Google Cloud project that contains the job.
 * @param {string} locationId - The regional endpoint location where the Dataflow job is running (for example, 'us-central1').
 * @param {string} jobId - The server-generated ID of the Dataflow job to get messages about.
 */
async function listJobMessages(projectId, locationId, jobId) {
  try {
    const request = {
      projectId,
      location: locationId,
      jobId,
    };

    const [messages] = await client.listJobMessages(request);

    console.log(`Retrieved ${messages.length} messages for job ${jobId}:`);
    for (const message of messages) {
      console.log(`[${message.messageImportance}] ${message.messageText}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Job ${jobId} not found in project ${projectId}.`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied accessing job ${jobId}.`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid arguments provided: ${err.message}`);
    } else {
      console.error(`API error: ${err.message}`);
    }
  }
}

module.exports = { listJobMessages };

Python

Para autenticarte en Dataflow, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import google.api_core.exceptions
from google.cloud import dataflow_v1beta3

client = dataflow_v1beta3.MessagesV1Beta3Client()


def list_job_messages(project_id: str, location_id: str, job_id: str) -> None:
    """Lists messages associated with a Dataflow job.

    Args:
        project_id: The Google Cloud project ID containing the Dataflow job.
        location_id: The regional endpoint containing the Dataflow job (for example, 'us-central1').
        job_id: The server-generated ID of the Dataflow job to list messages for.
    """
    request = dataflow_v1beta3.ListJobMessagesRequest(
        project_id=project_id,
        location=location_id,
        job_id=job_id,
    )

    try:
        page_result = client.list_job_messages(request=request)
        for message in page_result:
            print(f"Message ID: {message.id}")
            print(f"Time: {message.time}")
            print(f"Importance: {message.message_importance}")
            print(f"Text: {message.message_text}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"API call failed: {e}")

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .