ジョブの Cloud Logging からのログを表示する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
ジョブが Cloud Logging にログを書き込むように設定されている場合、このサンプルはそのログを取得します。ログには、ジョブの分析に役立つ情報が含まれています。たとえば、失敗したジョブのデバッグに役立ちます。
もっと見る
このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。
コードサンプル
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page provides code samples in C++, Go, Java, and Python for retrieving logs from Cloud Logging generated by Batch jobs.\u003c/p\u003e\n"],["\u003cp\u003eLogs are useful for analyzing and debugging Batch jobs, and this sample demonstrates how to access and view them.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples filter logs to find those specifically associated with a given job ID using its unique identifier, the job UID.\u003c/p\u003e\n"],["\u003cp\u003eThe page references how to set up Application Default Credentials (ADC) for authenticating with the Batch service during local development.\u003c/p\u003e\n"],["\u003cp\u003eLinks to the API reference documentation for each of the four languages, as well as a link to learn more about how to use logs to analyze a job, and a link to the sample browser, are all included for further information.\u003c/p\u003e\n"]]],[],null,["# View logs from Cloud Logging for a job\n\nIf the job has been set up to write logs to Cloud Logging, this sample retrieves its logs. Logs can provide information that is useful for analyzing your jobs. For example, logs can help you debug a failed job.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Analyze a job using logs](/batch/docs/analyze-job-using-logs)\n\nCode sample\n-----------\n\n### C++\n\n\nFor more information, see the\n[Batch C++ API\nreference documentation](/cpp/docs/reference/batch/latest).\n\n\nTo authenticate to Batch, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n #include \"google/cloud/batch/v1/batch_client.h\"\n #include \"google/cloud/logging/v2/logging_service_v2_client.h\"\n #include \"google/cloud/location.h\"\n #include \"google/cloud/project.h\"\n\n [](std::string const& project_id, std::string const& location_id,\n std::string const& job_id) {\n auto const project = google::cloud::Project(project_id);\n auto const location = google::cloud::Location(project, location_id);\n auto const name = location.FullName() + \"/jobs/\" + job_id;\n auto batch = google::cloud::batch_v1::BatchServiceClient(\n google::cloud::batch_v1::MakeBatchServiceConnection());\n auto job = batch.GetJob(name);\n if (!job) throw std::move(job).status();\n\n auto logging = google::cloud::logging_v2::LoggingServiceV2Client(\n google::cloud::logging_v2::MakeLoggingServiceV2Connection());\n auto const log_name = project.FullName() + \"/logs/batch_task_logs\";\n google::logging::v2::ListLogEntriesRequest request;\n request.mutable_resource_names()-\u003eAdd(project.FullName());\n request.set_filter(\"logName=\\\"\" + log_name +\n \"\\\" labels.job_uid=\" + job-\u003euid());\n for (auto l : logging.ListLogEntries(request)) {\n if (!l) throw std::move(l).status();\n std::cout \u003c\u003c l-\u003etext_payload() \u003c\u003c \"\\n\";\n }\n }\n\n### Go\n\n\nFor more information, see the\n[Batch Go API\nreference documentation](/go/docs/reference/cloud.google.com/go/batch/latest/apiv1).\n\n\nTo authenticate to Batch, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n\n \tbatch \"cloud.google.com/go/batch/apiv1\"\n \t\"cloud.google.com/go/batch/apiv1/batchpb\"\n \t\"cloud.google.com/go/logging\"\n \t\"cloud.google.com/go/logging/logadmin\"\n \t\"google.golang.org/api/iterator\"\n )\n\n // Retrieve the logs written by the given job to Cloud Logging\n func printJobLogs(w io.Writer, projectID string, job *batchpb.Job) error {\n \t// projectID := \"your_project_id\"\n\n \tctx := context.Background()\n \tbatchClient, err := batch.NewClient(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"NewClient: %w\", err)\n \t}\n \tdefer batchClient.Close()\n\n \tadminClient, err := logadmin.NewClient(ctx, projectID)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"Failed to create logadmin client: %w\", err)\n \t}\n \tdefer adminClient.Close()\n\n \tconst name = \"batch_task_logs\"\n\n \titer := adminClient.Entries(ctx,\n \t\t// Only get entries from the \"batch_task_logs\" log for the job with the given UID\n \t\tlogadmin.Filter(fmt.Sprintf(`logName = \"projects/%s/logs/%s\" AND labels.job_uid=%s`, projectID, name, job.Uid)),\n \t)\n\n \tvar entries []*logging.https://cloud.google.com/go/docs/reference/cloud.google.com/go/logging/latest/index.html#cloud_google_com_go_logging_Entry\n\n \tfor {\n \t\tlogEntry, err := iter.Next()\n \t\tif err == iterator.Done {\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\treturn fmt.Errorf(\"unable to fetch log entry: %w\", err)\n \t\t}\n \t\tentries = append(entries, logEntry)\n \t\tfmt.Fprintf(w, \"%s\\n\", logEntry.Payload)\n \t}\n\n \tfmt.Fprintf(w, \"Successfully fetched %d log entries\\n\", len(entries))\n\n \treturn nil\n }\n\n### Java\n\n\nFor more information, see the\n[Batch Java API\nreference documentation](/java/docs/reference/google-cloud-batch/latest/overview).\n\n\nTo authenticate to Batch, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.batch.v1.https://cloud.google.com/java/docs/reference/google-cloud-batch/latest/com.google.cloud.batch.v1.Job.html;\n import com.google.cloud.logging.v2.https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.cloud.logging.v2.LoggingClient.html;\n import com.google.logging.v2.https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.logging.v2.ListLogEntriesRequest.html;\n import com.google.logging.v2.https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.logging.v2.LogEntry.html;\n import java.io.IOException;\n\n public class ReadJobLogs {\n\n public static void main(String[] args) throws IOException {\n // TODO(developer): Replace these variables before running the sample.\n // Project ID or project number of the Cloud project hosting the job.\n String projectId = \"YOUR_PROJECT_ID\";\n\n // The job which logs you want to print.\n https://cloud.google.com/java/docs/reference/google-cloud-batch/latest/com.google.cloud.batch.v1.Job.html job = https://cloud.google.com/java/docs/reference/google-cloud-batch/latest/com.google.cloud.batch.v1.Job.html.newBuilder().build();\n\n readJobLogs(projectId, job);\n }\n\n // Prints the log messages created by given job.\n public static void readJobLogs(String projectId, https://cloud.google.com/java/docs/reference/google-cloud-batch/latest/com.google.cloud.batch.v1.Job.html job) throws IOException {\n // Initialize client that will be used to send requests. This client only needs to be created\n // once, and can be reused for multiple requests. After completing all of your requests, call\n // the `loggingClient.close()` method on the client to safely\n // clean up any remaining background resources.\n try (https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.cloud.logging.v2.LoggingClient.html loggingClient = https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.cloud.logging.v2.LoggingClient.html.create()) {\n\n https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.logging.v2.ListLogEntriesRequest.html request = https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.logging.v2.ListLogEntriesRequest.html.newBuilder()\n .addResourceNames(String.format(\"projects/%s\", projectId))\n .setFilter(String.format(\"labels.job_uid=%s\", job.https://cloud.google.com/java/docs/reference/google-cloud-batch/latest/com.google.cloud.batch.v1.Job.html#com_google_cloud_batch_v1_Job_getUid__()))\n .build();\n\n for (https://cloud.google.com/java/docs/reference/google-cloud-logging/latest/com.google.logging.v2.LogEntry.html logEntry : loggingClient.listLogEntries(request).iterateAll()) {\n System.out.println(logEntry.getTextPayload());\n }\n }\n }\n }\n\n### Python\n\n\nFor more information, see the\n[Batch Python API\nreference documentation](/python/docs/reference/batch/latest).\n\n\nTo authenticate to Batch, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from __future__ import annotations\n\n from typing import NoReturn\n\n from google.cloud import https://cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.logger.Logger.html#google_cloud_logging_v2_logger_Logger_batch_v1\n from google.cloud import logging\n\n\n def print_job_logs(project_id: str, job: batch_v1.https://cloud.google.com/python/docs/reference/batch/latest/google.cloud.batch_v1.types.Job.html) -\u003e NoReturn:\n \"\"\"\n Prints the log messages created by given job.\n\n Args:\n project_id: name of the project hosting the job.\n job: the job which logs you want to print.\n \"\"\"\n # Initialize client that will be used to send requests across threads. This\n # client only needs to be created once, and can be reused for multiple requests.\n log_client = logging.https://cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html(project=project_id)\n logger = log_client.https://cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html#google_cloud_logging_v2_client_Client_logger(\"batch_task_logs\")\n\n for log_entry in logger.list_entries(filter_=f\"labels.job_uid={job.uid}\"):\n print(log_entry.payload)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=batch)."]]