PHP용 Cloud Logging 라이브러리를 사용하여 PHP 애플리케이션에서 Cloud Logging에 직접 로그를 작성할 수 있습니다.
시작하기 전에
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
애플리케이션에서 PHP용 Cloud Logging 라이브러리를 사용하여 로그를 작성하려면 기본 리소스의 서비스 계정에 로그 작성자(roles/logging.logWriter)IAM 역할이 있어야 합니다.
대부분의 Google Cloud 환경에서는 이 역할이 있도록 기본 서비스 계정을 자동으로 구성합니다.
App Engine
Cloud Logging은 App Engine에 자동으로 사용 설정되며 앱의 기본 서비스 계정에는 기본적으로 로그 항목을 쓸 수 있는 IAM 권한이 있습니다.
하지만 애플리케이션 로그가 요청 로그와 상호 연결되도록 로그에 자동으로 메타데이터를 추가하는 PSR-3 로거를 사용하는 것이 좋습니다.
App Engine 가변형 환경용 데몬 구성
App Engine 가변형 환경에서 외부 데몬 프로그램을 사용하도록 PHP용 Cloud Logging 라이브러리를 구성하면 로그 처리량을 극대화하고 앱 지연 시간을 최소화할 수 있습니다. 이 기능을 사용하려면 app.yaml의 runtime_config 섹션에 다음 줄을 추가하세요.
enable_stackdriver_integration: true
Google Kubernetes Engine(GKE)
GKE에서는 기본 서비스 계정에 로그 작성자(roles/logging.logWriter) IAM 역할을 자동으로 부여합니다.
이 기본 서비스 계정과 함께 GKE용 워크로드 아이덴티티 제휴를 사용하여 워크로드에서 특정Google Cloud API에 액세스할 수 있게 하면 추가 구성은 필요하지 않습니다.
그러나 커스텀 IAM 서비스 계정과 함께 GKE용 워크로드 아이덴티티 제휴를 사용하는 경우에는 커스텀 서비스 계정에 로그 작성자 역할(roles/logging.logWriter)이 있어야 합니다.
필요한 경우 클러스터를 만들 때 다음 명령어를 사용하여 logging.write 액세스 범위를 추가할 수 있습니다.
Compute Engine VM 인스턴스를 사용할 때 각 인스턴스에 cloud-platform 액세스 범위를 추가합니다.Google Cloud 콘솔을 통해 새 인스턴스를 만들 때 인스턴스 만들기 패널의 ID 및 API 액세스 섹션에서 이 작업을 수행할 수 있습니다. 선택한 Compute Engine 기본 서비스 계정 또는 다른 서비스 계정을 사용하고 ID 및 API 액세스 섹션에서 모든 Cloud API에 대한 전체 액세스 허용을 선택하세요. 선택한 서비스 계정에 관계없이Google Cloud 콘솔의 IAM 및 관리자 섹션에서 로그 작성자 역할이 부여되었는지 확인합니다.
로컬 및 기타 위치에서 실행
자체 워크스테이션, 데이터 센터의 컴퓨터 또는 다른 클라우드 제공업체의 VM 인스턴스에서 라이브러리 실행을 포함하여 Google Cloud외부에서 PHP용 Cloud Logging 라이브러리를 사용하려면 로컬 환경에서 애플리케이션 기본 사용자 인증 정보(ADC)를 설정하여 PHP용 Cloud Logging 라이브러리에 인증해야 합니다.
로그 탐색기에서 리소스를 하나 이상 지정해야 하지만 어떤 리소스를 선택해야 할지 애매할 수 있습니다. 다음은 시작하는 데 도움이 되는 몇 가지 유용한 팁입니다.
애플리케이션을 App Engine에 배포하거나 App Engine 관련 라이브러리를 사용하는 경우 리소스를 GAE 애플리케이션으로 설정합니다.
애플리케이션을 Compute Engine에 배포하는 경우 리소스를 GCE VM 인스턴스로 설정합니다.
애플리케이션을 Google Kubernetes Engine에 배포하는 경우 클러스터의 로깅 구성에 따라 로그 항목의 리소스 유형이 결정됩니다. 기존 Google Cloud Observability 및 Google Cloud Observability Kubernetes Monitoring 솔루션에 대한 자세한 내용과 이러한 옵션이 리소스 유형에 미치는 영향을 알아보려면 Google Cloud Observability Kubernetes Monitoring으로 마이그레이션을 참조하세요.
애플리케이션에서 Cloud Logging API를 직접 사용하는 경우 API와 구성에 따라 리소스가 달라집니다. 예를 들어 애플리케이션에서 리소스를 지정하거나 기본 리소스를 사용할 수 있습니다.
로그 탐색기에 어떤 로그도 표시되지 않는 경우 모든 로그 항목을 보려면 고급 쿼리 모드로 전환하여 비어 있는 쿼리를 사용합니다.
고급 쿼리 모드로 전환하려면 로그 탐색기 상단의 메뉴(▾)를 클릭한 다음 고급 필터로 전환을 선택합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-09(UTC)"],[],[],null,["# Setting Up Cloud Logging for PHP\n\nYou can write logs to Cloud Logging from PHP applications by\nusing the Cloud Logging library for PHP directly.\n\n\u003cbr /\u003e\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Logging API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Logging API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com)\n\n\nInstalling the Cloud Logging library for PHP\n--------------------------------------------\n\nThe Cloud Logging library for PHP provides a simple [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)\nlogger implementation for PHP web frameworks.\n\nTo write logs from your app, add the Cloud Logging library for PHP to your composer.json: \n\n composer require google/cloud-logging\n\n### Creating a PSR-3 logger\n\nUse the following code to create a PSR-3 logger: \n\n use Google\\Cloud\\Logging\\LoggingClient;\n\n $logging = new LoggingClient([\n 'projectId' =\u003e $projectId\n ]);\n $logger = $logging-\u003epsrLogger('app');\n\n### Enabling batching option\n\n| **Note:** This step is optional.\n\nThe PSR-3 logger sends the logs synchronously. This means that\nwhenever you emit a log, it will add RPC latency to the user\nrequest. Especially if you emit multiple logs in a single request, the\nadded latency will be significant. You probably want to avoid that.\n\nThe following code creates a PSR-3 logger which will batch multiple\nlogs into one single RPC calls: \n\n $logger = LoggingClient::psrBatchLogger('app');\n\nBy default, this logger batches the logs within a single process. On\nApp Engine flexible environment, you can configure the Cloud Logging library for PHP for\neven higher throughput and lower latency. For details, see\n[Configuring the logging daemon](#gae-config).\n\n### Configuring the Cloud Logging library for PHP\n\nYou can customize the behavior of the Cloud Logging library for PHP. See\n[the configuration document](/php/docs/reference/cloud-logging/latest/LoggingClient#_Google_Cloud_Logging_LoggingClient____construct__)\nfor a list of possible configuration options.\n\nUsing the PSR-3 logger\n----------------------\n\nOnce the logger is created, you can use the logger in your\napplication: \n\n $logger-\u003einfo('Hello World');\n $logger-\u003eerror('Oh no');\n\n\u003cbr /\u003e\n\nFor more information on installation, see the\n[documentation](https://github.com/googleapis/google-cloud-php/tree/master/Logging) for the\nCloud Logging library for PHP. You can also report issues using the\n[issue tracker](https://github.com/googleapis/google-cloud-php/issues).\n\nWrite logs with the Cloud Logging client library\n------------------------------------------------\n\nFor information on using the Cloud Logging client library for\nPHP directly, see [Cloud Logging Client Libraries](/logging/docs/reference/libraries).\n\nRun on Google Cloud\n-------------------\n\nFor an application to write logs by using the Cloud Logging library for PHP, the\nservice account for the underlying resource must have the\n[Logs Writer (`roles/logging.logWriter`)](/logging/docs/access-control#permissions_and_roles) [IAM](/iam/docs/understanding-roles) role.\nMost Google Cloud environments automatically configure the default\nservice account to have this role.\n\n### App Engine\n\nCloud Logging is automatically enabled for App Engine, and your app's\n[default service account](/appengine/docs/standard/php7/service-account) has\nthe IAM permissions by default to write log entries.\n\nFor more information, see [Writing and viewing\nlogs](/appengine/docs/standard/php7/writing-application-logs).\n\n\nHowever, we recommend that you use the PSR-3 logger which automatically\nadds metadata to your logs so that your application logs are\ncorrelated to the request logs.\n\n#### Configuring the daemon for App Engine flexible environment\n\nIn the App Engine flexible environment, you can configure the\nCloud Logging library for PHP to use an external daemon program to maximize the\nlog throughput and minimize the app's latency. To enable this feature,\nadd the following line to `runtime_config` section in `app.yaml`: \n\n enable_stackdriver_integration: true\n\n### Google Kubernetes Engine (GKE)\n\n[GKE](/kubernetes-engine/docs) automatically grants the default service account\nthe [Logs Writer (`roles/logging.logWriter`)](/logging/docs/access-control#permissions_and_roles) IAM role.\nIf you use\n[Workload Identity Federation for GKE](/kubernetes-engine/docs/concepts/workload-identity)\nwith this default service account to let workloads access specific\nGoogle Cloud APIs, then no additional configuration is required.\nHowever, if you use Workload Identity Federation for GKE with a\ncustom IAM service account, then ensure that the custom service\naccount has the role of Logs Writer (`roles/logging.logWriter`).\n\nIf needed, you can also use the following command to add the `logging.write`\naccess scope when creating the cluster: \n\n gcloud container clusters create example-cluster-name \\\n --scopes https://www.googleapis.com/auth/logging.write\n\n### Compute Engine\n\n| **Note:** To use the Cloud Logging library for PHP on a **Compute Engine** VM instance, you do not need to install the Cloud Logging agent.\n\nWhen using [Compute Engine](/compute/docs) VM instances, add the `cloud-platform`\naccess scope to each instance. When creating a new instance through the\nGoogle Cloud console, you can do this in the **Identity and API access** section\nof the **Create Instance** panel. Use the Compute Engine default service\naccount or another service account of your choice, and select\n**Allow full access to all Cloud APIs** in the **Identity and API access**\nsection. Whichever service\naccount you select, ensure that it has been granted the\n[Logs Writer role](/logging/docs/access-control#permissions_and_roles) in the **IAM \\& Admin** section of the\nGoogle Cloud console.\n\nRun locally and elsewhere\n-------------------------\n\nTo use the Cloud Logging library for PHP outside of Google Cloud,\nincluding running the library on your own workstation, on your data center's\ncomputers, or on the VM instances of another cloud provider, you must\nset up Application Default Credentials (ADC) in your local environment to\nauthenticate to the Cloud Logging library for PHP.\n\nFor more information, see\n[Set up ADC for on-premises or another cloud provider](/docs/authentication/set-up-adc-on-premises).\n\nView the logs\n-------------\n\nIn the Google Cloud console, go to the **Logs Explorer** page:\n\n[Go to **Logs Explorer**](https://console.cloud.google.com/logs/query)\n\n\u003cbr /\u003e\n\nIf you use the search bar to find this page, then select the result whose subheading is\n**Logging**.\n\nIn the Logs Explorer, you must specify one or more resources, but the resource\nselection might not be obvious. Here are some tips to help you get\nstarted:\n\n- If you are deploying your application to App Engine or using the\n App Engine-specific libraries, set your resource to\n **GAE Application**.\n\n- If you are deploying your application on Compute Engine, set the resource\n to **GCE VM Instance**.\n\n- If you are deploying your application on Google Kubernetes Engine, your\n cluster's logging configuration determines the resource type of the log\n entries. For a detailed\n discussion on the Legacy Google Cloud Observability and the Google Cloud Observability\n Kubernetes Monitoring solutions, and how those options affect the\n resource type, see\n [Migrating to Google Cloud Observability Kubernetes Monitoring](/monitoring/kubernetes-engine/migration#stackdriver-options).\n\n- If your application is using the Cloud Logging API directly,\n the resource is dependent on the API and your configuration. For example,\n in your application, you can specify a resource or use a default resource.\n\n- If you don't see any logs in the Logs Explorer, to see all log entries,\n switch to the advanced query mode and use an empty query.\n\n 1. To switch to the advanced query mode, click **menu** (▾) at the top of the Logs Explorer and then select **Convert to advanced filter**.\n 2. Clear the content that appears in the filter box.\n 3. Click **Submit Filter**.\n\n You can examine the individual entries to identify your resources.\n\nFor additional information, see [Using the Logs Explorer](/logging/docs/view/logs-explorer-interface)."]]