Build and save queries by using the Logging query language

This document describes how to retrieve and analyze logs when you use theLogs Explorer by writing queries in the query-editor field and byselecting from predefined filter options. Thequeries you build are written in theLogging query language.

You can also save your queries in the Logs Explorer page, or by using theLogging API methodsavedQueries.create.

Before you begin

The Logs Viewer role (roles/logging.viewer) provides access to view logs.For example, when granted this role, you can write and run queries. You can alsosave queries as private queries, and run both private and shared queries.However, this role doesn't let you save or modify shared queries. If you wantto save or modify shared queries, then ensure that you have been granted theLogging Admin role (roles/logging.admin), which provides full access toCloud Logging.

Do one of the following:

  • To get the permissions that you need to write and run queries, to run and save private queries, andto run shared queries, ask your administrator to grant you theLogs Viewer (roles/logging.viewer) IAM role on your project.

  • To get the permissions that you need to write and run queries, to run and save private queries,and to run, create, and manage shared queries, ask your administrator to grant you theLogging Admin (roles/logging.admin) IAM role on your project.

For more information about the necessary IAM permissions, seePermissions for the Google Cloud console.

Build queries

To build queries by using the Google Cloud console, do the following:

  1. In the Google Cloud console, go to theLogs Explorer page:

    Go toLogs Explorer

    If you use the search bar to find this page, then select the result whose subheading isLogging.

  2. Select the Google Cloud project or other Google Cloudresource for which you want to view logs.

  3. Use theQuery pane to build your query.

    TheQuery pane provides multiple ways to build and run query expressions:

    • Search for text across all log fields.
    • Select options from filter menus.
    • Write or modify queries by using the query editor.
    • View and run saved, recent, and suggested queries from theQuery library.

Search for text across log fields

To search for text across all log fields and find all matching log entries,in the toolbar of the query pane, enter your search terms in theSearch all fields field. The search terms you enter inthis field are converted into a Logging query language expression.

You can search for words and phrases, and your search terms can includeBoolean operators andregular expressions:

  • To perform a case-sensitive search, you must use aregular expression.

  • To perform a case-insensitive search along token boundaries, enter the searchterms without backticks or double quotes.

    For example, to search for log entries that contain the wordhello andthe wordworld, enterhello world. This command, which is converted toSEARCH("hello world"), matches log entries that contain the tokenshello andworld, in any order. Because the search is case-insensitive,the search also matches a log entry that contains the tokensHello andWorld. The search doesn't match the tokenworlds.

  • To perform a case-insensitive search for a phrase along token boundaries,wrap the phrase in backticks.

    For example, to search for the phrasehello world,enter`hello world`.This command, which is converted toSEARCH("`hello world`"),matches log entries that contain the tokenhello world.The search doesn't match the tokenhello worlds.

  • To perform a case-insensitive search for a substring, wrap the text indouble quotes. For example,"hello world" matchesHello World andHello world. The same query also matcheshello worlds, because thesearch isn't performed along token boundaries.

    Note: Substring searches are slower than token-based searches. Therefore, werecommend that you use token-based searches when possible.

To see your search terms within the query expression, enableShow query.

After you enter your search terms, clickRun query or press theEnterkey. The results of the query are displayed in theQuery results pane.

Boolean operators and the search field

TheSearch all fields field supports the usage of theBoolean operatorsAND,OR, andNOT. If you use Booleanoperators, then do the following:

If you don't include any operators, all search terms and phrases are joined byAND. That is, you can omit theAND operator between search terms.

Examples

Suppose you enterrequest AND localhost OR client into theSearch all fields field. Due to theprecedence rules,the search terms are converted into the following query:

SEARCH("`request`")SEARCH("`localhost`") OR SEARCH("client")

Next, suppose that you want to list log entries that contain the stringclient or that contain bothrequest andlocalhost. You can't use theSearch all fields field to generate a query that matchesyour goal. When your search terms contain both anAND and anORstatement, theprecedence rules specify that theOR operationis always performed first. Parentheses aren't treated as special characterswhen they are included in search terms.

However, you can use theQuery pane and enter a query. In theQuerypane, you can use parentheses to specify order in which commands areprocessed. For example, the following query satisfies your goal:

(SEARCH("`request`") AND SEARCH("`localhost`")) OR SEARCH("`client`")

Operator precedence

TheAND andOR operators areshort-circuit operators.You can combineAND andOR rules in the same expression. For example, whenthe two operators are mixed, the expressiona AND b OR c AND d turns into thefollowing Logging query language expression:

"a""b" OR "c""d"

TheNOT operator has the highest precedence, followed byOR andANDin that order.

TheNOT operator performs a negation of the subsequent term. For example,NOT error returns log entries that don't containerror. You can also replacetheNOT operator with the- (minus) operator. For example, the following twoqueries are the same:

"response" AND "successful" AND NOT "error"
"response successful" -"error"

This logic also works with a phrase, if the- (minus) operator is outside thequotation marks. For example, the following two queries are the same:

-"response successful"
NOT "response successful"

Construct queries with filter menus

You can use the filter menus in theQuery pane to add resource, log name,log severity, and correlation parameters to the query-editor field. Theseoptions correspond to theLogEntry fields for all logs inLogging.

The options in theResource andLog name menus are derived from thelog entries that are stored by Cloud Logging.

  • Resource: Lets you specify theresource.type andassociatedresource.labels. You can select a single resource type usingthis filter menu, and zero or more resource labels to apply to yourquery. The resource parameters are joined by the logical operatorAND.
  • Log name: Lets you specify thelogName. You can selectmultiple log names to apply to your query. When selecting multiple lognames, the logical operatorOR is used.
  • Severity: Lets you specify theseverity. You can selectmultiple severity levels at the same time to add to apply to your query.When selecting multiple severity levels, the logical operatorOR isused.
  • Correlate by: Lets you group and view log entries in a "parent-child"format. For more information, seeCorrelate log entries.

To use any of the filter menus, do the following:

  1. Expand theMenu on anyof the filter menus in theQuery pane.

  2. Refine the filter parameters.

  3. ClickApply. You see the parameters in the query-editor field.

    To see your search terms within the query expression, enableShow query.

  4. After you review the query, clickRun query. The results of thequery are displayed in theQuery results pane.

For certain Compute Engine resource types, such asgce_instance andgce_network, you see the resource name with the resource ID as subtext. Forexample, for thegce_instance resource type, you see the VM namealongside the VM ID. The resource names help you identify the correctresource ID, on which you can build queries.

View logs by time range

There are two ways to display logs that were written in a specific time range:

  1. Use the time-range selector.
  2. Include a timestamp expression in the query-editor field.

Use the time-range selector

The options in the time-range selector let you select from preset time options,specify a custom start and end time, or center the time range around a specifictimestamp. For example, if you want to viewthe data for the past week, then selectLast 1 week from the time-rangeselector.

You can also set your time zone preferences by using the time-range selector.

Include a timestamp expression in the query-editor field

To add a timestamp expression directly to the query-editor field,use theLogging query language.

If the query-editor field contains an expression with a timestamp, then thetime-range selector is disabled, and the query uses the timestamp expression asits time-range restriction. If a query doesn't use a timestamp expression, thenthe query uses the time-range selector as its time-range restriction.

Write advanced queries using the Logging query language

You can use theLogging query language to buildmore advanced queries in the Logs Explorer query-editor field:

  1. If you don't see the query-editor field in theQuery pane, enableShow query.

  2. Enter your query expressions directly into the query-editor field.

    If you added any search terms in the search field or selected anyparameters in the filter menus, then those also appear in thequery-editor field and are evaluated as part of your query expression.

  3. After you review your query, clickRun query.

    Logs that match your query are listed under theQuery resultspane. TheHistogramandLog fieldspanes also adjust according to the query expression.

For examples of common queries you might want to use, seeSample queries using the Logs Explorer.

Note: The length of a query can't exceed 20,000 characters.

Use recent queries

When you run any query, the query is added to theQuery library, which contains the last 10,000 uniquequeries over a 30-day period.

To view your recent queries, select theQuery librarybutton in the primary toolbar. For recent queries, you have the followingoptions:

  • Stream: To run the query andstream the results, choose thisoption.
  • Run: To run the query, choose this option.
  • More options:Lets you view the query expression with the options to run the query or saveit to your list ofSaved queries. You can also select the query directlyto get these options.

    To save the query, do the following:

    1. ClickSave. TheSave query dialog opens.
    2. Complete the following fields:

      • Name (Required): Provide a name for your query. Names are limited to64 characters.
      • Description (Optional): Provide a description to help identify thepurpose of the query.
      • Include summary fields (Optional): EnableInclude summary fieldsand enter thesummary fields that you want to display.
      • Truncate summary fields (Optional): EnableTruncate summary fields and select the number of characters totruncate to and whether truncation occurs at the beginning or end of thefields.
    3. ClickSave query. The query is now available in yourSaved queries list.

You can also sort and filter your recent queries; the filter matches on the textin your query expression.

Save and share queries

Note: If your data is managed through anAssured Workloads environment,then this feature might be impacted or restricted. For information, seeRestrictions and limitations in Assured Workloads.

Saved queries let you store query expressions to help you explore your logs moreconsistently and efficiently. The Logs Explorer features aQuery library, where you can access your saved queries. You can alsosave your queries by using the Logging API methodsavedQueries.create.

You can save your query so that it is private and visible only to you, or youcan share it with other members of the Google Cloud project. Once you sharea query, the query is no longer owned by you, and any member in the projectwith the necessary permissions can access the query.

Console

To save a query expression that you've built in the query-editor field, do thefollowing:

  1. ClickSave in theQuery pane. TheSave query dialog opens,with your query expression in the query-editor field.

  2. Complete the following fields:

    • Name (Required): Provide a name for your query. Names are limited to64 characters.
    • Description (Optional): Provide a description to help identify thepurpose of the query.
    • Include custom summary fields (Optional): EnableInclude summaryfields and enter thesummary fields that you wantto display.
    • Truncate summary fields (Optional): EnableTruncate summary fields and select the number of characters totruncate to and whether truncation occurs at the beginning or end of thefields.
    • Share with project: Optionally, enableShare with project toshare your query with other members of the Google Cloud project.
  3. ClickSave query. Your saved queries appear in alist under theSaved tab.

To run a saved query, clickRun. To run the query andstreamthe results, clickStream.

To modify a saved query, selectMore options,and then selectEdit. You can also select the query,make modifications, and then save the modified query.

To delete a saved query, selectMore options,and then selectDelete.

You can also sort and filter your saved queries; the filter matches the textin your query expression.

API

To save a query by using the Logging API, use thesavedQueries.create method. For more information about this method, itsparameters, and the response data, see the reference page forsavedQueries.create.

You can execute thesavedQueries.create method by using theAPIs Explorer widget on the method's reference page.For Logs Explorer queries, you must specify theloggingQueryfield. The following example illustrates a sample request body, whichcontains an instance ofSavedQuery:

{  "parent": "projects/my-project/locations/global"  "savedQueryId": "compute-query"  {    "displayName": "compute-admin-activity-query",    "description": "Queries for Compute Engine Admin Activity logs.",    "loggingQuery":      {        "filter": resource.type="gce_instance" AND log_id("cloudaudit.googleapis.com/activity"),      },    "visibility": "PRIVATE"  }}

To share the query with other members of the Google Cloud project, specifya value ofSHARED in thevisibility field.

View saved queries

You can view both private queries and queries that are shared with other membersin the Google Cloud project by clicking theQuerylibrary button:

Console

  1. In the Google Cloud console, go to theLogs Explorer page:

    Go toLogs Explorer

    If you use the search bar to find this page, then select the result whose subheading isLogging.

  2. Select the Google Cloud project or other Google Cloudresource for which you want to view logs.

  3. Click theQuery library button, and clickSaved.

You can sort the table by any header. TheVisibility column indicatesif the queries are shared or private:

  • Shared: Queries that are shared with other members of theGoogle Cloud project.
  • Private: Queries that you have saved and are only visible to you.

API

You can use the Logging API to view private and sharedqueries by using thesavedQueries.list method.

For example, the following request body lists all shared Logs Explorerqueries with a wildcard location ID:

{  "parent": "name": projects/PROJECT_ID/locations/-  "visibility": "SHARED"  "filter": "explorer"}

Use suggested queries

Logging generates suggested queries based on the context of yourGoogle Cloud project, such as the Google Cloud products you're using.Suggested queries can help you identify issues and provide you with insightsinto the overall health of your systems. For example, detecting that you'reusing Google Kubernetes Engine, Logging might suggest a query that findsall the error logs for your containers.

To view and run suggested queries, click theQuery library button and clickSuggested. In theSuggested tab, youhave the following options:

  • Stream: To run the query andstream the results, choose thisoption.
  • Run: To run the query, choose this option.
  • More options:Lets you view the details of the query expression with the options to run thequery or save it. You can also select the query directlyto get these options.

    To review the details of a suggested query, do either of the following:

    • Select the query's row.

    • ClickMoreand selectView. TheQuery details dialog opens.

    In theQuery details dialog, you see the query and the options toRun,Stream orSave as:

    • To save the query, do the following:

      1. ClickSave query.
      2. Complete the fields in theSave query dialog.

      The edited query shows up in yourSaved list, where you can choose torun the query later.

    • To run the query now, clickRun. The query runs and appears in thequery-editor field.

    • To run the query now andstream the results, clickStream.

    • To close the dialog and return to the suggested queries list, clickClose.

Note the following expected behaviors:

  • Successive page loads might not show the same queries in the same order.
  • You might see zero suggested queries.
  • Sometimes running a suggested query returns zero logs.

Select queries from the library

Logging provides a library of queries based on common usecases and Google Cloud products. These queries can help you efficientlyfind logs during time-critical troubleshooting sessions and explore your logsto better understand what Logging data is available.

To view and run the library's queries, do the following:

  1. In the Google Cloud console, go to theLogs Explorer page:

    Go toLogs Explorer

    If you use the search bar to find this page, then select the result whose subheading isLogging.

  2. Select the Google Cloud project or other Google Cloudresource for which you want to view logs.

  3. Click theQuery library button. You see categoriesof available queries and subsets of queries based on Google Cloudproducts. To narrow the selection of queries that you see, click any of theproducts.

    You can also use the search field to search the available queries bycategory, description, or the contents of the query expression.

  4. To review a query expression, do either of the following:

    a. Click the query's row.

    b. ClickMore and selectView.

  5. In theQuery details dialog, you see the query and the options toRun,Stream orSave as:

    • To save the query, do the following:

      1. ClickSave query.
      2. Complete the fields in theSave query dialog.

      The edited query shows up in yourSaved list, where you can choose torun the query later.

    • To run the query now, clickRun. The query runs and appears in thequery-editor field.

    • To run the query now andstream the results, clickStream.

    • To close the dialog and return to the suggested queries list, clickClose.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.