Cloud Logging에서 작업의 로그 보기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Cloud Logging에 로그를 작성하도록 작업이 설정된 경우 이 샘플은 로그를 검색합니다. 로그는 작업을 분석하는 데 유용한 정보를 제공할 수 있습니다. 예를 들어 로그는 실패한 작업을 디버깅할 수 있습니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 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)."]]