All Products
Search
Document Center

Container Service for Kubernetes:Collect container logs (standard output and files)

Last Updated:Aug 24, 2026

Deploy LoongCollector in DaemonSet mode and create a collection configuration in the SLS console to centralize Kubernetes container log collection and enable structured processing for efficient querying and analysis.

Requirements

  • Runtime environment

    • Supports Container Service for Kubernetes (ACK) (managed and dedicated editions) and self-managed Kubernetes clusters.

    • Kubernetes 1.10.0 or later that supports Mount propagation: HostToContainer.

    • Container runtime (Docker and Containerd only)

      • Docker:

        • Requires access to docker.sock.

        • Standard output collection supports only the JSON log driver.

        • Supports only the overlay and overlay2 storage drivers. To use other types of storage drivers, manually mount the log directory.

      • Containerd: Requires access to containerd.sock.

  • Resource requirements: LoongCollector (Logtail) runs with the system-cluster-critical high-priority class. Deploying it on a resource-constrained cluster may evict existing Pods.

    • CPU: Reserve at least 0.1 core.

    • Memory: Reserve at least 150 MB for the collection component and at least 100 MB for the controller component.

    • Actual usage depends on the collection rate, the number of monitored directories and files, and send congestion. Keep resource usage below 80% of the specified limits.

  • Permission requirements: To deploy, the Alibaba Cloud account or RAM user must have the AliyunLogFullAccess permission.

    To create custom policies with fine-grained permissions, copy the permissions from the AliyunCSManagedLogRolePolicy system policy and grant them to the target RAM user or role.

Collection configuration

  1. Install LoongCollector: Deploy LoongCollector in DaemonSet mode. This ensures that a collection container runs on each node in the cluster to collect logs from all containers on that node.

    For the Sidecar pattern, use Collect text logs from Kubernetes pods (Sidecar pattern).
  2. Create a Logstore: A Logstore stores collected logs.

  3. Create and configure log collection rules

    1. Global and input configuration: Define the name of the collection configuration and specify the source and scope of log collection.

    2. Log processing and structuring: Configure processing rules based on the log format.

      • Multiline logs: Handle log entries that span multiple lines, such as Java exception stacks or Python tracebacks, by defining a first-line regular expression to identify the start of each entry.

      • Structured parsing: Configure parsing plugins, such as regular expressions, delimiters, or NGINX mode, to extract raw strings into structured key-value pairs, enabling efficient querying and analysis.

    3. Log filtering: Configure collection blacklists and content filtering rules to filter out unwanted log data. This helps reduce redundant data transmission and storage.

    4. Log categorization: Configure log topics and tags to distinguish logs from different services, containers, or path sources.

  4. Query and analysis configuration: Full-text indexing is enabled by default for keyword searches. For precise queries and analysis of structured fields, enable field indexes to improve search efficiency.

  5. Verification and troubleshooting: After you complete the configuration, verify that logs are collected successfully. If you encounter issues such as data collection failure, heartbeat failure, or parsing errors, see Troubleshooting FAQ.

Step 1: Install LoongCollector

LoongCollector is the next-generation log collection agent by Simple Log Service and the successor to Logtail. LoongCollector and Logtail cannot coexist. To install Logtail, see Install, run, upgrade, and uninstall Logtail.

Install LoongCollector using one of the methods below. For parameter details, see Installation and configuration. If LoongCollector or Logtail is already installed, skip to Step 2: Create a logstore.

Note

Changing the host time while LoongCollector (Logtail) is running can cause duplicate collection or data loss.

ACK cluster

Install LoongCollector in the Container Service for Kubernetes console. By default, logs are sent to a Simple Log Service Project within the current Alibaba Cloud account.

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. Click the name of the target cluster.

  3. In the left-side navigation pane, click Add-ons.

  4. On the Logs and Monitoring tab, find LoongCollector, and click Install.

    Note

    When you create a cluster, you can select Enable Log Service on the Component Configurations page. You can select Create Project or Select Project.

    After the installation is complete, Simple Log Service automatically creates the following resources in the current account. You can view them in the Simple Log Service console.

    Resource type

    Resource name

    Description

    Project

    k8s-log-${cluster_id}

    Isolates logs from different services.

    For flexible log management, Create a Project.

    Machine group

    k8s-group-${cluster_id}

    A collection of log collection nodes. Kubernetes node IP addresses change dynamically as the cluster scales in or out, so identifying a machine group by IP address can cause heartbeat failures. Therefore, machine groups in Kubernetes scenarios use a custom identifier. For more information, see Guide to associating machine groups with collection configurations.

    Important

    The LoongCollector component does not create a logstore named config-operation-log. If this logstore already exists, LoongCollector does not write logs to it.

Self-managed cluster

  1. Connect to the Kubernetes cluster and run the appropriate command for your region:

    China regions

    wget https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongcollector/k8s-custom-pkg/3.0.12/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh

    Regions outside China

    wget https://aliyun-observability-release-ap-southeast-1.oss-ap-southeast-1.aliyuncs.com/loongcollector/k8s-custom-pkg/3.0.12/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh
  2. Go to the loongcollector-custom-k8s-package directory and modify the ./loongcollector/values.yaml configuration file.

    # ===================== Required Information =====================
    # The name of the Project to which logs from this cluster are sent. Example: k8s-log-custom-sd89ehdq
    projectName: ""
    # The region where the Project is located. Example: cn-shanghai
    region: ""
    # The UID of the Alibaba Cloud account that owns the Project. Enclose the UID in quotation marks (""). Example: "123456789"
    aliUid: ""
    # The network type. Valid values: Internet and Intranet. Default value: Internet.
    net: Internet
    # The AccessKey ID and AccessKey secret of the Alibaba Cloud account or RAM user. The account or RAM user must have the AliyunLogFullAccess system policy permission.
    accessKeyID: ""
    accessKeySecret: ""
    # A custom cluster ID. The ID can contain only uppercase letters, lowercase letters, digits, and hyphens (-).
    clusterID: ""
  3. In the loongcollector-custom-k8s-package directory, run the following command to install LoongCollector and its dependencies:

    bash k8s-custom-install.sh install
  4. After the installation is complete, verify that the components are running.

    If a pod fails to start, verify the configurations in the values.yaml file and ensure the required images have been pulled.
    # Check the pod status
    kubectl get po -n kube-system | grep loongcollector-ds

    Simple Log Service also automatically creates the following resources. You can view them in the Simple Log Service console.

    Resource type

    Resource name

    Description

    Project

    The value of projectName that you specified in the values.yaml file

    Isolates logs from different services.

    For flexible log management, Create a Project.

    Machine group

    k8s-group-${cluster_id}

    A collection of log collection nodes. Kubernetes node IP addresses change dynamically as the cluster scales in or out, so identifying a machine group by IP address can cause heartbeat failures. Therefore, machine groups in Kubernetes scenarios use a custom identifier. For more information, see Guide to associating machine groups with collection configurations.

    Important

    The LoongCollector component does not create a logstore named config-operation-log. If this logstore already exists, LoongCollector does not write logs to it.

Step 2: Create a logstore

A logstore is the basic storage unit for logs in SLS.

  1. Log in to the Simple Log Service console and click the name of the target project.

  2. In the left-side navigation pane, select imageLogstores, click +, and create a logstore:

    • Logstore Name: Enter a name that is unique within the project. This name cannot be changed after creation.

    • Logstore Type: Select Standard or Query based on the feature comparison.

    • Billing Mode:

      • Pay-by-feature (Cannot Be Changed): You are billed independently for each resource, such as storage, index, and read/write operations. This mode is suitable for small-scale use cases or when feature usage is uncertain.

      • Pay-by-ingested-data: You are billed only for the volume of raw data that you write. This mode provides 30 days of free storage and free features, such as data transformation and delivery. This mode is suitable for business use cases where the storage period is close to 30 days or the data processing pipeline is complex.

    • Data Retention Period: The number of days to retain logs. The value can be from 1 to 3,650. A value of 3,650 indicates permanent retention. The default value is 30 days.

    • Keep the default values for the other settings and click OK. Manage a logstore.

Step 3: Configure a log collection rule

Define which logs to collect, how to parse them, and how to filter content, then apply the configuration to a machine group.

  1. On the image Logstore page, click the image icon before the name of the target Logstore to expand it.

  2. Click the image icon next to Import Data. In the Quick Data Import dialog box, select a template based on the log source and click Integrate Now:

  3. In the Machine Group Configurations section, complete the configuration and click Next:

    • Scenario: Select Docker Containers.

    • Deployment method: Select ACK DaemonSet or Self-managed Cluster in DaemonSet Mode.

    • From the Source Machine Group list, move the system-created machine group k8s-group-${cluster_id} to the Applied Machine Group list.

  4. On the Logtail Configuration page, configure the following settings, and then click Next.

1. Global and input configuration

In this step, define the name, log source, and scope for your collection configuration.

Container standard output

Global Configurations

  • Configuration Name: Enter a custom name for the collection configuration. The name must be unique within the Project and cannot be modified after creation. Naming conventions:

    • Can contain only lowercase letters, digits, hyphens (-), and underscores (_).

    • Must start and end with a lowercase letter or a digit.

Input configuration

  • Turn on the Stdout and Stderr and/or Standard Error toggles. Both are enabled by default.

    Important

    We recommend against enabling both standard output and standard error simultaneously, as this can cause out-of-order log collection.

Cluster text logs

Global Configurations:

  • Configuration Name: Enter a custom name for the collection configuration. The name must be unique within the Project and cannot be modified after creation. Naming conventions:

    • Can contain only lowercase letters, digits, hyphens (-), and underscores (_).

    • Must start and end with a lowercase letter or a digit.

Input Configurations:

  • File Path Type:

    • Path in Container: Collect log files from within a container.

    • Host Path: Collect logs from local services on the host machine.

  • File Path: The absolute path for log collection.

    • Linux: Must start with a forward slash (/), such as /data/mylogs/**/*.log. This path indicates all files ending with .log in the /data/mylogs directory and its subdirectories.

    • Windows: Must start with a drive letter, such as C:\Program Files\Intel\**\*.log.

  • Maximum Directory Monitoring Depth: The maximum directory depth that the ** wildcard in the File Path can match. The default is 0 (current directory only), and the valid range is 0 to 1,000.

    We recommend setting this to 0 and configuring the path to the directory containing the log files.

2. Log processing and structuring

Configure processing rules to convert raw logs into structured, searchable data. Add a log sample before configuring rules.

On the Logtail Configuration page, in the Processor Configurations area, click Add Sample Log and enter the log content you want to collect. The system uses the sample to identify the log format and help generate regular expressions and parsing rules, which simplifies the configuration process.

Use case 1: Process multiline logs

Logs such as Java stack traces and JSON objects often span multiple lines. By default, these are split into incomplete records. Enable multiline mode and configure a first-line regex to merge consecutive lines into complete records.

Example:

Unprocessed raw log

In default mode, each line is treated as a separate log, breaking up the stack trace and losing context.

With multiline mode enabled, a first-line regular expression identifies a complete log, preserving its semantic structure.

image

image

image

Procedure: On the Logtail Configuration page, in the Processor Configurations area, enable Multi-line Mode.

  • Type: Select Custom or Multi-line JSON.

    • Custom: If the raw log format is not fixed, you must configure a Regex to Match First Line to identify the starting line of each log entry.

      • Regex to Match First Line: You can generate this automatically or enter it manually. The expression must match an entire line of data. For the example above, the matching regex is \[\d+-\d+-\w+:\d+:\d+,\d+]\s\[\w+]\s.*.

        • Auto-generate: Click Auto-generate Regular Expression. In the Log Sample text box, select the log content to extract and click Generate Regex.

        • Manual input: Click Manually Enter Regular Expression. After entering the expression, click Validate.

    • Multi-line JSON: Select this option when raw logs are in standard JSON format. LoongCollector automatically handles line breaks within single JSON entries.

  • Processing Method If Splitting Fails:

    • Discard: If a text segment does not match the first-line regular expression, it is discarded.

    • Retain Single Line: Unmatched text is split and retained according to the original single-line mode.

Use case 2: Structure logs

When raw logs are unstructured text (e.g., Nginx access logs), direct querying is inefficient. LoongCollector provides parsing plugins that convert raw logs into structured key-value pairs for analysis, monitoring, and alerting.

Example:

Unprocessed raw log

Log after structured parsing

192.168.*.* - - [15/Apr/2025:16:40:00 +0800] "GET /nginx-logo.png HTTP/1.1" 0.000 514 200 368 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.*.* Safari/537.36"
body_bytes_sent: 368
http_referer: -
http_user_agent : Mozi11a/5.0 (Nindows NT 10.0; Win64; x64) AppleMebKit/537.36 (KHTML, like Gecko) Chrome/131.0.x.x Safari/537.36
remote_addr:192.168.*.*
remote_user: -
request_length: 514
request_method: GET
request_time: 0.000
request_uri: /nginx-logo.png
status: 200
time_local: 15/Apr/2025:16:40:00

Procedure: In the Processor Configurations area of the Logtail Configuration page:

  1. Add a parsing plugin: Click Add Processor and configure a regex, delimiter, or JSON parsing plugin based on your log format. For this NGINX example, select Native Processor > Data Parsing (NGINX Mode).

  2. NGINX Log Configuration: copy the entire log_format definition from your Nginx server's configuration file (nginx.conf) and paste it into this text box.

    Example:

    log_format main  '$remote_addr - $remote_user [$time_local] "$request" ''$request_time $request_length ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent"';
    Important

    The format definition here must exactly match the format that generates the logs on the server; otherwise, parsing will fail.

  3. Common parameters: The following parameters are common to multiple data parsing plugins and function in the same way.

    • Original field: Specifies the source field to parse. Defaults to content, which is the entire collected log entry.

    • Keep original field on failure: Recommended. If a log fails to parse (e.g., due to a format mismatch), this option retains the original log content in the specified original field.

    • Keep original field on success: When selected, the original log content is retained even after successful parsing.

3. Log filtering

Collecting low-value or irrelevant logs, such as those at the DEBUG or INFO level, wastes storage, increases costs, impairs query performance, and can introduce security risks. Implement fine-grained filtering policies for efficient and secure log collection.

Content filtering

Filter logs based on field content, such as collecting only logs where the level is WARNING or ERROR.

Example:

Unprocessed raw logs

Collect only WARNING or ERROR logs

{"level":"WARNING","timestamp":"2025-09-23T19:11:40+0800","cluster":"yilu-cluster-0728","message":"Disk space is running low","freeSpace":"15%"}
{"level":"ERROR","timestamp":"2025-09-23T19:11:42+0800","cluster":"yilu-cluster-0728","message":"Failed to connect to database","errorCode":5003}
{"level":"INFO","timestamp":"2025-09-23T19:11:47+0800","cluster":"yilu-cluster-0728","message":"User logged in successfully","userId":"user-123"}
{"level":"WARNING","timestamp":"2025-09-23T19:11:40+0800","cluster":"yilu-cluster-0728","message":"Disk space is running low","freeSpace":"15%"}
{"level":"ERROR","timestamp":"2025-09-23T19:11:42+0800","cluster":"yilu-cluster-0728","message":"Failed to connect to database","errorCode":5003}

Procedure: In the Processor Configurations area of the Logtail Configuration page:

Click Add Processor and select Native Processor > Data Filtering.

  • Field Name: The log field to filter on.

  • Field Value: The regular expression for filtering. Only full-text matching is supported; partial keyword matching is not.

Collection blacklist

Use a blacklist to exclude specified directories or files, preventing the upload of irrelevant or sensitive logs.

Procedure: On the Logtail Configuration page, navigate to the Input Configurations > Other Input Configurations area, enable Collection Blacklist, and click Add.

Supports exact and wildcard matching for directories and filenames. The only supported wildcards are the asterisk (*) and question mark (?).
  • File Path Blacklist: The file paths to ignore. Examples:

    • /home/admin/private*.log: Ignores all files in the /home/admin/ directory that start with "private" and end with ".log".

    • /home/admin/private*/*_inner.log: Ignores files ending with "_inner.log" located in subdirectories that start with "private" under the /home/admin/ directory.

  • File Blacklist: The filenames to ignore during collection. Example:

    • app_inner.log: Ignores all files named app_inner.log.

  • Directory Blacklist: The directory path cannot end with a forward slash (/). Examples:

    • /home/admin/dir1/: The directory blacklist will not take effect.

    • /home/admin/dir*: Ignores all files within subdirectories of /home/admin/ that start with "dir".

    • /home/admin/*/dir: Ignores all files in any second-level subdirectory named "dir" under /home/admin/. For example, files in /home/admin/a/dir are ignored, but files in /home/admin/a/b/dir are collected.

Container filtering

Set collection conditions based on container metadata—such as environment variables, Pod labels, Namespaces, and container names—to precisely control which containers' logs are collected.

Procedure: In the Input Configurations area of the Logtail Configuration page, enable Container Filtering and click Add.

Multiple conditions are combined with a logical "AND". All regular expression matching is based on Go's RE2 engine, which has limitations compared to engines like PCRE. Ensure your expressions comply with the Appendix: Regular Expression Usage Limits (Container Filtering).
  • Environment Variable Blacklist/Whitelist: Filter containers based on their environment variables.

  • K8s Pod Label Blacklist/Whitelist: Filter Pods based on their labels.

  • K8s Pod Name Regex Match: Collect logs from Pods whose names match the specified regular expression.

  • K8s Namespace Regex Match: Selects containers for collection based on the Namespace name.

  • K8s Container Name Regex Match: Collect logs from containers whose names match the specified regular expression.

  • Container Label Blacklist/Whitelist: Collect logs from containers with matching labels. This is intended for Docker scenarios and not recommended for K8s scenarios.

4. Log categorization

In scenarios where multiple applications share a log format, distinguishing the source is difficult. Configure log topics and tags to enable automated context association and logical categorization.

Log topics

When multiple applications or instances share a log format but have different paths (e.g., /apps/app-A/run.log and /apps/app-B/run.log), distinguishing the source is difficult. To solve this, you can generate a log topic based on the machine group, a custom name, or file path extraction to differentiate logs from various business or path sources.

Procedure: Navigate to Global Configurations > Other Global Configurations > Log Topic Type and select a topic generation method from the following three options:

  • Machine group topic: When a collection configuration is applied to multiple machine groups, LoongCollector automatically uses the machine group name as the value of the __topic__ field. This is suitable for scenarios where logs are categorized by host cluster.

  • Custom: The format is customized://<custom_topic_name>, for example, customized://app-login. This is suitable for static topic scenarios with fixed business identifiers.

  • File path extraction: Extracts key information from the full path of the log file to dynamically mark the log source. This is suitable when multiple users or applications share the same log filename but have different paths.

    When multiple users or services write logs to different top-level directories with identical sub-paths and filenames, the source cannot be distinguished by filename alone. For example:

    /data/logs
    ├── userA
    │   └── serviceA
    │       └── service.log
    ├── userB
    │   └── serviceA
    │       └── service.log
    └── userC
        └── serviceA
            └── service.log

    In this case, you can configure file path extraction and use a regular expression to extract key information from the full path. The matched result is then uploaded to the Logstore as the log topic.

    Extraction rule: Regex capturing groups

    When you configure a regular expression, the system automatically determines the output field format based on the number and naming of capturing groups, as follows:

    In the regular expression for a file path, forward slashes (/) must be escaped.

    Capturing group type

    Use case

    Generated field

    Regex example

    Example path

    Generated field

    Single capturing group (one (.*?))

    A single dimension is needed to distinguish sources (e.g., username, environment).

    Generates a __topic__ field.

    \/logs\/(.*?)\/app\.log

    /logs/userA/app.log

    __topic__:userA

    Multiple unnamed capturing groups (multiple (.*?))

    Multiple dimensions are needed but without semantic labels.

    Generates Tag fields formatted as __tag__:__topic_{i}__:value, where {i} is the capturing group index.

    \/logs\/(.*?)\/(.*?)\/app\.log

    /logs/userA/svcA/app.log

    __tag__:__topic_1__:userA;

    __tag__:__topic_2__:svcA

    Multiple named capturing groups (using (?P<name>.*?))

    Multiple dimensions are needed with clear, semantic field names for easier querying and analysis.

    Generates Tag fields formatted as __tag__:{name}:value.

    \/logs\/(?P<user>.*?)\/(?P<service>.*?)\/app\.log

    /logs/userA/svcA/app.log

    __tag__:user:userA;

    __tag__:service:svcA

Log tagging

Enable the log tag enrichment feature to extract key information from container environment variables or Kubernetes Pod labels and attach it as Tags for fine-grained log grouping.

Procedure: On the Logtail Configuration page, in the Input Configurations area, enable Log Tag Enrichment and click Add.

  • Environment Variables: Configure an environment variable name and a Tag key. The environment variable's value will be stored as the Tag's value.

    • Environment variable name: The name of the environment variable to extract.

    • Tag key: The key for the new Tag.

  • Pod Labels: Configure a Pod label key and a Tag key. The Pod label's value will be stored as the Tag's value.

    • Pod label key: The key of the Kubernetes Pod label to extract.

    • Tag key: The key for the new Tag.

5. Output configuration

By default, all logs are sent to the current Logstore with lz4 compression. To distribute logs from the same source to different Logstores, follow the steps below.

Multi-destination dynamic distribution

Important
  • Multi-destination dynamic distribution is available only for LoongCollector 3.0.0 and later. This feature is not supported by Logtail.

  • You can configure a maximum of five output destinations.

  • After you configure multiple output destinations, this collection configuration will no longer appear in the current Logstore's list of collection configurations. To view, modify, or delete the configuration, see How do I manage multi-destination distribution configurations?.

Procedure: On the Logtail Configuration page, in the Output Configurations area:

  1. Click image to expand the output configuration.

  2. Click Add Output Targets and complete the following configuration:

    • Logstores: Select the target Logstore.

    • Compression Method: Supports lz4 and zstd.

    • Route Settings: Route logs based on Tag fields. Logs matching the routing configuration are sent to the target Logstore. If this is left empty, all collected logs are sent to the target Logstore.

      • Tag Name: The Tag key used for routing. Enter the key directly (e.g., __path__) without the __tag__: prefix. Tag fields fall into two categories:

        Tags are explained in Manage LoongCollector Collection Tags.
        • Agent-related: Generated by the collection agent and are independent of any plugins. Examples include __hostname__ and __user_defined_id__.

        • Input plugin-related: Provided and enriched by input plugins. Examples include __path__ from file collection and _pod_name_ or _container_name_ from K8s collection.

      • Tag Value: Logs whose Tag value matches this setting are sent to the target Logstore.

      • Discard this tag?: If enabled, this Tag field will not be included in the uploaded logs.

Step 4: Query and analysis

After you configure log processing and plugins, click Next to proceed to the Query and Analysis Configurations page:

  • By default, the system enables the full-text index, which lets you search raw log content by keyword.

  • To query data by specific fields, click Automatic Index Generation after the Preview Data loads. Log Service generates a field index based on the first log entry in the preview data.

After completing the configuration, click Next to finalize the collection process.

Step 5: Validate and troubleshoot

After you create and apply a collection configuration to a machine group, the system automatically deploys it and starts collecting incremental logs.

View collected logs

  1. Confirm that the log file has new content: LoongCollector only collects incremental logs. Run tail -f /path/to/your/log/file and trigger business operations to ensure that new logs are being written.

  2. Search for logs: Go to the Search & Analyze page of the target Logstore. Click Search & Analyze. The default time range is the last 15 minutes. Check whether new logs are ingested. Each collected container text log includes the following fields by default:

    Parameter

    Description

    __tag__:__hostname__

    The name of the container host.

    __tag__:__path__

    The path of the log file within the container.

    __tag__:_container_ip_

    The IP address of the container.

    __tag__:_image_name_

    The name of the image used by the container.

    __tag__:_pod_name_

    The name of the Pod.

    __tag__:_namespace_

    The namespace of the Pod.

    __tag__:_pod_uid_

    The unique identifier (UID) of the Pod.

Troubleshoot common issues

Machine group heartbeat failure

  1. Check the user identifier: If your server is not an ECS instance, or if the ECS instance and the Project belong to different Alibaba Cloud accounts, ensure the correct user identifier exists in the specified directory.

    • On Linux, run the cd /etc/ilogtail/users/ && touch <uid> command to create a user identifier file.

    • Windows: Go to the C:\LogtailData\users\ directory and create an empty file named <uid>.

    The user identifier is configured correctly if the specified path contains a file whose name is the Alibaba Cloud account ID of the current Project.

  2. Check the machine group identifier: If you use a custom identifier for a machine group, check if the user_defined_id file exists in the specified directory. If the file exists, check if its content matches the custom identifier configured for the machine group.

    • Linux:

      # Configure the custom identifier. If the directory does not exist, create it manually.
      echo "user-defined-1" > /etc/ilogtail/user_defined_id
    • Windows: In the C:\LogtailData directory, create a file named user_defined_id and write the custom identifier to the file. (If the directory does not exist, create it manually.)

  3. If the user identifier and machine group identifier are configured correctly, refer to Troubleshooting LoongCollector (Logtail) machine groups for further troubleshooting.


Log collection errors or format errors

This issue typically occurs when your network connection and basic configuration are correct, but the log content does not match the parsing rules. To diagnose the problem, view the specific error message:

  1. On the Logtail Configuration page, click the name of the LoongCollector (Logtail) configuration that has collection errors. On the Log Collection Error tab, click Select Time Range to set the query time.

  2. In the section, view the alert type of the error log and refer to Common error types for data collection to find the corresponding solution.

Next steps

  1. Log query and analysis:

  2. Data visualization: Use visualization dashboards to monitor key metric trends.

  3. Data anomaly alerting: Set up alert policies to detect data anomalies in real time.

Troubleshooting container log collection

  1. Verify that new logs are being generated in the target log file. Logtail does not collect data until new logs appear.

2. Check Logtail runtime logs

  1. Log in to the Logtail container:

    1. Query the Logtail pod.

      kubectl get po -n kube-system | grep logtail

      The output is similar to the following:

      logtail-ds-****d                                             1/1       Running    0          8d
      logtail-ds-****8                                             1/1       Running    0          8d
    2. Log in to the pod.

      kubectl exec -it -n kube-system logtail-ds-****d -- bash

      Replace logtail-ds-****d with your actual pod ID.

  1. Check Logtail runtime logs:

    Logtail logs are stored in the /usr/local/ilogtail/ directory within the Logtail container. The filenames are ilogtail.LOG and logtail_plugin.LOG. Log in to the Logtail container and run the following commands to view the logs:

    # Go to the /usr/local/ilogtail/ directory.
    cd /usr/local/ilogtail
    
    # View the ilogtail.LOG and logtail_plugin.LOG files.
    cat ilogtail.LOG
    cat logtail_plugin.LOG

    Check the error logs for the alert type and find the corresponding solution in Common errors in Simple Log Service data collection.

3. Check the machine group heartbeat

Go to the Resource Group > Machine Groups page and click the name of the target machine group. In the Machine Group Configurations > Machine Group Status section, view the Heartbeat status and record the number of nodes that have an "OK" status.

  1. Check the number of worker nodes in the container cluster.

    1. Connect to an ACK cluster using kubectl.

    2. Check the number of worker nodes in the cluster.

      kubectl get node | grep -v master

      The output is similar to the following:

      NAME                                 STATUS    ROLES     AGE       VERSION
      cn-hangzhou.i-bp17enxc2us3624wexh2   Ready     <none>    238d      v1.10.4
      cn-hangzhou.i-bp1ad2b02jtqd1shi2ut   Ready     <none>    220d      v1.10.4
  2. Compare the number of nodes with an OK heartbeat status to the number of worker nodes in the container cluster. Then, follow the appropriate troubleshooting steps based on the result.

    • The heartbeat status of all nodes in the machine group is Failed:

      • For a self-managed cluster, verify that the {regionId}, {aliuid}, {access-key-id}, and {access-key-secret} parameters are correct.

        If they are incorrect, run the helm del --purge alibaba-log-controller command to delete the installation package and then reinstall it.

    • The number of nodes with a heartbeat status of OK is less than the number of worker nodes in the cluster.

      • Check if a DaemonSet was manually deployed by using a YAML file.

        1. Run the following command. If a result is returned, it indicates that a DaemonSet was previously deployed manually using a YAML file.

          kubectl get po -n kube-system -l k8s-app=logtail
        2. Download the latest version of the DaemonSet template.

        3. Configure parameters such as ${your_region_name}, ${your_aliyun_user_id}, and ${your_machine_group_name} with your actual values.

        4. Update the resource.

          kubectl apply -f ./logtail-daemonset.yaml

4. Check collection filters

In the SLS console, check the Logtail collection configuration. Verify that the IncludeLabel, ExcludeLabel, IncludeEnv, and ExcludeEnv settings in the Logtail configuration meet your collection requirements.

  • In this context, "label" refers to the container label from Docker's inspect output, not a Kubernetes label.

  • To test your filters, temporarily remove the IncludeLabel, ExcludeLabel, IncludeEnv, and ExcludeEnv settings and check if logs are collected. If they are, your filter configuration is incorrect.

FAQ

Manage multi-destination distribution configurations

Since multi-destination distribution configurations apply to multiple logstores, manage them from the Project-level management page:

  1. Log on to the Simple Log Service console and click the name of the target Project.

  2. On the Project page, in the left-side navigation pane, click imageResource Group > Configurations.

    Note

    This page manages all collection configurations within the Project, including configurations for logstores that were accidentally deleted.

Send ACK logs to a cross-account Project

You can send container logs to a Simple Log Service (SLS) Project in another Alibaba Cloud account by manually installing the LoongCollector (Logtail) component in the ACK cluster and configuring it with the target account's Alibaba Cloud account ID or access credential (AccessKey).

Scenario description: If you need to collect log data into another account's SLS Project for organizational, permission, or monitoring purposes, manually install LoongCollector (Logtail) to enable cross-account collection.

Procedure: Follow these steps to manually install LoongCollector. For information about how to install Logtail, see Install and configure Logtail.

  1. Connect to the Kubernetes cluster and run the appropriate command for your region:

    China regions

    wget https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongcollector/k8s-custom-pkg/3.0.12/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh

    Regions outside China

    wget https://aliyun-observability-release-ap-southeast-1.oss-ap-southeast-1.aliyuncs.com/loongcollector/k8s-custom-pkg/3.0.12/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh
  2. Go to the loongcollector-custom-k8s-package directory and modify the ./loongcollector/values.yaml configuration file.

    # ===================== Required Information =====================
    # The name of the Project to which logs from this cluster are sent. Example: k8s-log-custom-sd89ehdq
    projectName: ""
    # The region where the Project is located. Example: cn-shanghai
    region: ""
    # The UID of the Alibaba Cloud account that owns the Project. Enclose the UID in quotation marks (""). Example: "123456789"
    aliUid: ""
    # The network type. Valid values: Internet and Intranet. Default value: Internet.
    net: Internet
    # The AccessKey ID and AccessKey secret of the Alibaba Cloud account or RAM user. The account or RAM user must have the AliyunLogFullAccess system policy permission.
    accessKeyID: ""
    accessKeySecret: ""
    # A custom cluster ID. The ID can contain only uppercase letters, lowercase letters, digits, and hyphens (-).
    clusterID: ""
  3. In the loongcollector-custom-k8s-package directory, run the following command to install LoongCollector and its dependencies:

    bash k8s-custom-install.sh install
  4. After the installation is complete, verify that the components are running.

    If a pod fails to start, verify the configurations in the values.yaml file and ensure the required images have been pulled.
    # Check the pod status
    kubectl get po -n kube-system | grep loongcollector-ds

    Simple Log Service also automatically creates the following resources. You can view them in the Simple Log Service console.

    Resource type

    Resource name

    Description

    Project

    The value of projectName that you specified in the values.yaml file

    Isolates logs from different services.

    For flexible log management, Create a Project.

    Machine group

    k8s-group-${cluster_id}

    A collection of log collection nodes. Kubernetes node IP addresses change dynamically as the cluster scales in or out, so identifying a machine group by IP address can cause heartbeat failures. Therefore, machine groups in Kubernetes scenarios use a custom identifier. For more information, see Guide to associating machine groups with collection configurations.

    Important

    The LoongCollector component does not create a logstore named config-operation-log. If this logstore already exists, LoongCollector does not write logs to it.

Use multiple configurations for the same source

By default, to prevent data duplication, Simple Log Service (SLS) allows only one collection configuration to collect logs from each source:

  • A text log file can match only one Logtail collection configuration.

  • A container's standard output (stdout):

    • If you use the new version of the standard output template, stdout can be collected by only one standard output collection configuration by default.

    • If you use the old version of the standard output template, no extra configuration is required, and multiple collections are supported by default.

  1. Log on to the Simple Log Service console and go to the target Project.

  2. In the left-side navigation pane, choose imageLogstores and find the target logstore.

  3. Click the image icon next to its name to expand the logstore.

  4. Click Logtail Configuration. In the list of configurations, find the target Logtail configuration and click Manage Logtail Configuration in the Actions column.

  5. On the Logtail configuration page, click Edit and scroll to the Input Configurations section:

    • To collect text file logs, enable Allow File to Be Collected for Multiple Times.

    • To collect container standard output, enable Allow Collection by Different Logtail Configurations.

Dependency error when uninstalling loongcollector

Problem: When you try to uninstall the loongcollector (logtail-ds) component in Container Service for Kubernetes (ACK), you receive an error that the component's dependencies are not met.

Dependencies of addons are not met: terway-eniip depends on logtail-ds(>0.0) whose version is v3.x.x.x-aliyun or will be v3.x.x.x-aliyun.

Cause: The terway-eniip network plugin has log collection enabled, which creates a dependency on the loongcollector (logtail-ds) component. Therefore, ACK does not allow you to uninstall loongcollector (logtail-ds) until you remove this dependency.

Solution: Follow these steps to remove the dependency and then uninstall the component:

  1. Log on to the ACK console.

  2. In the cluster list, click the name of the target cluster to go to its details page.

  3. In the left-side navigation pane, click Add-ons.

  4. In the list of add-ons, search for the terway-eniip component and click Disable Logging.

  5. In the dialog box that appears, click OK.

  6. After the configuration takes effect, try to uninstall the loongcollector (logtail-ds) component again.

Delayed or truncated last log entry

Cause: Log truncation typically occurs when a log file is missing a final line feed, or when a multiline log entry, such as an exception stack, has not been fully written. Because the collector cannot determine if the log entry is complete, the last log entry may be split or delayed. How this is handled depends on your LoongCollector (Logtail) version:

  • Versions earlier than 1.8:
    If the last line of a log lacks a line feed (carriage return), or if a multiline log block is incomplete, the collector waits for the next write operation to trigger an output. This can significantly delay the last log entry until a new log is written.



  • Version 1.8 and later:
    These versions introduce a timeout flush mechanism to prevent logs from getting stuck. When an incomplete log line is detected, the system starts a timer. After the timeout period expires, the current content is automatically submitted to ensure the log is eventually collected.



    • Default timeout: 60 seconds (ensures data integrity in most scenarios)

    • You can adjust this value based on your requirements. However, we recommend that you do not set it to 0, as this may cause log truncation or partial data loss.

Solution:

You can extend the waiting time to ensure that a complete log entry is written before it is collected:

  1. Log on to the Simple Log Service console and go to the target Project.

  2. In the left-side navigation pane, choose imageLogstores and find the target logstore.

  3. Click the image icon next to its name to expand the logstore.

  4. Click Logtail Configuration. In the list of configurations, find the target Logtail configuration and click Manage Logtail Configuration in the Actions column.

  5. On the Logtail configuration page, click Edit.

    • Go to Input Configurations > Other Input Configurations > Advanced Parameters and add the following JSON configuration to customize the timeout period.

      {
        "FlushTimeoutSecs": 1
      }
      • Default value: Determined by the default_reader_flush_timeout startup parameter, which is typically a few seconds.

      • Unit: Seconds.

      • Recommended value: ≥ 1 second. We recommend that you do not set it to 0, as this may cause log truncation or partial data loss.

  6. After you complete the configuration, click OK.

LoongCollector network failover and recovery

If LoongCollector (Logtail) detects an internal network connectivity issue, such as a failure or timeout, it automatically switches to the public network. This failover mechanism ensures reliable log collection and prevents backlogs or data loss.

  • LoongCollector: Automatically switches back to the internal network after the network recovers.

  • Logtail: Does not automatically switch back. You must restart it to restore internal network communication.

Appendix: Native processors

On the Logtail Configuration page, in the Processor Configurations area, you can add processing plug-ins to structure raw logs. To add a processing plug-in to an existing collection configuration, you can follow these steps:

  1. In the navigation pane on the left, choose imageLogstores and find the destination Logstore.

  2. Click image to the left of its name to expand the Logstore.

  3. Click Logtail Configuration. In the configuration list, find the destination Logtail configuration and click Manage Logtail Configuration in the Actions column.

  4. On the Logtail configuration page, click Edit.

This section introduces only commonly used processing plug-ins that cover common log processing scenarios. For more features, see Extension processing plug-ins.
Important

Rules for combining plug-ins (applies to LoongCollector / Logtail 2.0 and later):

  • Native and extension processing plug-ins can be used independently or in combination as needed.

  • We recommend that you use native processing plug-ins first, because they offer better performance and higher stability.

  • When native features cannot meet business requirements, you can add extension processing plug-ins after the configured native ones to perform supplementary processing.

Order constraint:

All plug-ins are executed sequentially in the order they are configured, which forms a processing chain. Note: All native processing plug-ins must precede any extension processing plug-ins. After you add any extension processing plug-in, you cannot add more native processing plug-ins.

Regular expression parsing

This processor uses a regular expression to parse logs into key-value pairs. You can then query and analyze each extracted field independently.

Example:

Raw log

Parsed result

127.0.0.1 - - [16/Aug/2024:14:37:52 +0800] "GET /wp-admin/admin-ajax.php?action=rest-nonce HTTP/1.1" 200 41 "http://www.example.com/wp-admin/post-new.php?post_type=page" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
body_bytes_sent: 41
http_referer: http://www.example.com/wp-admin/post-new.php?post_type=page
http_user_agent: Mozilla/5.0 (Windows NT 10.0; Win64; ×64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0
remote_addr: 127.0.0.1
remote_user: -
request_method: GET
request_protocol: HTTP/1.1
request_uri: /wp-admin/admin-ajax.php?action=rest-nonce
status: 200
time_local: 16/Aug/2024:14:37:52 +0800

Steps: On the Logtail Configuration page, in the Processor Configurations area, click Add Processor, and select Native Processor > Data Parsing (Regex Mode):

  • Regular Expression: Matches log entries. You can either generate one automatically or enter it manually.

    • To generate a regular expression automatically:

      • Click Generate Regular Expression.

      • In the Log Sample box, highlight the content to extract.

      • Click Generate.

        image

    • Manually enter a regular expression based on your log format.

    After configuring the expression, click Validate to test if it correctly parses your log sample.

  • Extracted Field: Assign a name (key) to the extracted content (value).

  • For information about other parameters, see the description of common configuration parameters in Scenario 2: Structured logs.


Delimiter parsing

This processor uses a delimiter to parse logs into key-value pairs. You can use single or multi-character delimiters.

Example:

Raw log

Using a specified character, split a field

05/May/2025:13:30:28,10.10.*.*,"POST /PutData?Category=YunOsAccountOpLog&AccessKeyId=****************&Date=Fri%2C%2028%20Jun%202013%2006%3A53%3A30%20GMT&Topic=raw&Signature=******************************** HTTP/1.1",200,18204,aliyun-sdk-java
ip:10.10.*.*
request:POST /PutData?Category=YunOsAccountOpLog&AccessKeyId=****************&Date=Fri%2C%2028%20Jun%202013%2006%3A53%3A30%20GMT&Topic=raw&Signature=******************************** HTTP/1.1
size:18204
status:200
time:05/May/2025:13:30:28
user_agent:aliyun-sdk-java

Procedure: On the Logtail Configuration page, in the Processor Configurations area, click Add Processor, and select Native Processor > Data Parsing (Delimiter Mode):

  • Delimiter: The character that separates fields in the log.

    Example: For a CSV file, select Custom and enter a comma (,).

  • Quote: The character used to enclose a field value. This is necessary if a field value might contain the delimiter, as it prevents incorrect splitting.

  • Extracted Field: Assign a field name (Key) for each column in sequential order. The field names must adhere to the following rules:

    • Can contain only letters, digits, and underscores (_).

    • Must start with a letter or an underscore (_).

    • Maximum length: 128 bytes.

  • For information about other parameters, see the description of common configuration parameters in Scenario 2: Structured logs.


Standard JSON parsing

This processor parses a log entry that is a JSON object into key-value pairs.

Example:

Raw log

Parsed result

{"url": "POST /PutData?Category=YunOsAccountOpLog&AccessKeyId=U0Ujpek********&Date=Fri%2C%2028%20Jun%202013%2006%3A53%3A30%20GMT&Topic=raw&Signature=pD12XYLmGxKQ%2Bmkd6x7hAgQ7b1c%3D HTTP/1.1", "ip": "10.200.98.220", "user-agent": "aliyun-sdk-java", "request": {"status": "200", "latency": "18204"}, "time": "05/Jan/2025:13:30:28"}
ip: 10.200.98.220
request: {"status": "200", "latency" : "18204" }
time: 05/Jan/2025:13:30:28
url: POST /PutData?Category=YunOsAccountOpLog&AccessKeyId=U0Ujpek******&Date=Fri%2C%2028%20Jun%202013%2006%3A53%3A30%20GMT&Topic=raw&Signature=pD12XYLmGxKQ%2Bmkd6x7hAgQ7b1c%3D HTTP/1.1
user-agent:aliyun-sdk-java

Procedure: On the Logtail Configuration page, in the Processor Configurations section, click Add Processor, and select Native Processor > Data Parsing (JSON Mode):

  • Original Field: The default value is content. This field stores the raw log content to be parsed.

  • For information about other parameters, see the description of common configuration parameters in Scenario 2: Structured logs.


Nested JSON parsing

This processor expands a nested JSON object into key-value pairs. You control the expansion with the JSON expansion depth setting.

Example:

Raw log

Result (depth: 0)

Result (depth: 1)

{"s_key":{"k1":{"k2":{"k3":{"k4":{"k51":"51","k52":"52"},"k41":"41"}}}}}
0_s_key_k1_k2_k3_k41:41
0_s_key_k1_k2_k3_k4_k51:51
0_s_key_k1_k2_k3_k4_k52:52
1_s_key:{"k1":{"k2":{"k3":{"k4":{"k51":"51","k52":"52"},"k41":"41"}}}}

Procedure: On the Logtail Configuration page, in the Processor Configurations section, click Add Processor, and select Extended Processor > Expand JSON Field:

  • Original Field: The name of the original field to expand, such as content.

  • JSON Expansion Depth: The number of levels to expand within the JSON object. 0 expands all levels (default), 1 expands only the top level, and so on.

  • Character to Concatenate Expanded Keys: The character used to join keys from nested objects. Defaults to an underscore (_).

  • Name Prefix of Expanded Keys: A prefix to add to the name of each expanded key.

  • Expand Array: Enable this option to expand an array into indexed key-value pairs.

    For example, {"k":["a","b"]} expands to  {"k[0]":"a","k[1]":"b"}.

    To rename an expanded field (e.g., from prefix_s_key_k1 to new_field_name), add a Rename Fields processor after this one.
  • For information about other parameters, see the description of common configuration parameters in Scenario 2: Structured logs.


JSON array parsing

Use the json_extract function to extract a JSON object from a JSON array.

Example:

Raw log

Parsed result

[{"key1":"value1"},{"key2":"value2"}]
json1:{"key1":"value1"}
json2:{"key2":"value2"}

Procedure: On the Logtail Configuration page, in the Processor Configurations section, set the Processing Method to SPL. Then, configure the SPL statement to use the json_extract function to extract JSON objects from the JSON array.

Example: From the log field content, extract elements from a JSON array and store the results respectively in the new fields json1 and json2.

* | extend json1 = json_extract(content, '$[0]'), json2 = json_extract(content, '$[1]')

Apache log parsing

This processor parses Apache access logs into key-value pairs based on your Apache LogFormat directive.

Example:

Raw log

Apache Common Log Format combined parsing

1 192.168.1.10 - - [08/May/2024:15:30:28 +0800] "GET /index.html HTTP/1.1" 200 1234 "https://www.example.com/referrer" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.X.X Safari/537.36"
http_referer:https://www.example.com/referrer
http_user_agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.X.X Safari/537.36
remote_addr:192.168.1.10
remote_ident:-
remote_user:-
request_method:GET
request_protocol:HTTP/1.1
request_uri:/index.html
response_size_bytes:1234
status:200
time_local:[08/May/2024:15:30:28 +0800]

Procedure: On the Logtail Configuration page, in the Processor Configurations section, click Add Processor, and select Native Processor > Data Parsing (Apache Mode):

  • Log Format: combined

  • APACHE LogFormat Configuration: The system automatically populates this field based on the selected Log Format.

    Important

    Verify that the auto-populated content is identical to the LogFormat directive defined in your server's Apache configuration file, which is typically located at /etc/apache2/apache2.conf.

  • For other parameters, see the description of common configuration parameters in Scenario 2: Structured Log.


Data masking

Mask sensitive data in your logs.

Example:

Raw log

Masked result

[{'account':'1812213231432969','password':'04a23f38'}, {'account':'1812213685634','password':'123a'}]
[{'account':'1812213231432969','password':'********'}, {'account':'1812213685634','password':'********'}]

Procedure: On the Logtail Configuration page, in the Processor Configurations section, click Add Processor, and select Native Processor > Data Masking:

  • Original Field: The source field containing the content to be masked.

  • Data Masking Method:

    • const: Replaces sensitive content with a specified string.

    • md5: Replaces sensitive content with its MD5 hash value.

  • Replacement String: The string to use for masking. This is required when the Data Masking Method is set to const.

  • Content Expression that Precedes Replaced Content: A regular expression in RE2 syntax to locate the content immediately before the sensitive data.

  • Content Expression to Match Replaced Content: A regular expression in RE2 syntax to match the sensitive data that you want to replace.


Time parsing

Parses the time field in the log and sets the parsed result as the log's __time__ field.

Example:

Raw log

Parsed result

{"level":"INFO","timestamp":"2025-09-23T19:11:47+0800","cluster":"yilu-cluster-0728","message":"User logged in successfully","userId":"user-123"}

image

Procedure: On the Logtail Configuration page, in the Processor Configurations section, click Add Processor, and select Native Processor > Time Parsing:

  • Original Field: The source field that contains the time string to parse.

  • Time Format: The time format that corresponds to the time string in your logs.

  • Time Zone: The time zone of the log's time field. If unspecified, it defaults to the time zone of the machine running LoongCollector (Logtail).

Appendix: Regular expression limitations (container filtering)

Regular expressions for container filtering use the Go RE2 engine. Compared to other engines like PCRE, the RE2 engine has several syntax limitations. Keep the following in mind when writing regular expressions:

1. Named group syntax differences

Go uses the (?P<name>...) syntax to define a named group and does not support the (?<name>...) syntax from PCRE.

  • Correct: (?P<year>\d{4})

  • Incorrect: (?<year>\d{4})

2. Unsupported regular expression features

The RE2 engine does not support the following common but complex regular expression features. Avoid using them:

  • Assertions: (?=...), (?!...), (?<=...), and (?<!...)

  • Conditional expressions: (?(condition)true|false)

  • Recursive matching: (?R) and (?0)

  • Subprogram references: (?&name) and (?P>name)

  • Atomic groups: (?>...)

3. Recommendations

Use a tool such as Regex101 to debug your regular expressions. To ensure compatibility, select the Golang (RE2) mode for validation. If you use any unsupported syntax, the plugin will fail to parse or match the expression.

Appendix: Container standard output version comparison

To improve storage efficiency and collection consistency, the log metadata format for container standard output has been upgraded. In the new format, all metadata is consolidated under the __tag__ field to optimize storage and standardize the format.

  1. Core advantages of the new version

    • Significant performance gains

      • Refactored in C++, the new version delivers a 180% to 300% performance improvement over the previous Go implementation.

      • It supports native plugins for data processing and multi-threaded parallel processing to fully utilize system resources.

      • It supports flexible combinations of native and Go plugins to handle complex scenarios.

    • Enhanced reliability

      • It supports a log rotation queue for container standard output and unifies the log collection mechanism with the file collection mechanism. This unification ensures high reliability during rapid log rotation.

    • Lower resource consumption

      • CPU usage is reduced by 20% to 25%.

      • Memory usage is reduced by 20% to 25%.

    • Enhanced O&M consistency

      • Unified parameter configuration: The configuration parameters for the new container standard output collection plugin are consistent with those for the file collection plugin.

      • Unified metadata management: The field names and storage location for container metadata are now consistent with the file collection format. As a result, the consumer side only needs one set of processing logic.

  2. Feature comparison of new and old versions

    Feature

    Previous behavior

    New behavior

    Storage method

    Metadata is embedded in the log content as individual fields.

    Metadata is consolidated under the __tag__ field.

    Storage efficiency

    Each log entry contains a full, duplicate set of metadata, which consumes more storage space.

    Multiple log entries from the same source can reuse metadata, saving storage costs.

    Format consistency

    The format is inconsistent with the file collection format.

    Field names and storage structure are now consistent with the file collection format, providing a unified experience.

    Query access method

    You can query metadata fields directly by name, such as _container_name_.

    You must access the corresponding key-value pair through the __tag__ object, such as __tag__: _container_name_.

  3. Container metadata field mapping

    Previous parameter

    New parameter

    _container_ip_

    __tag__:_container_ip_

    _container_name_

    __tag__:_container_name_

    _image_name_

    __tag__:_image_name_

    _namespace_

    __tag__:_namespace_

    _pod_name_

    __tag__:_pod_name_

    _pod_uid_

    __tag__:_pod_uid_

    In the new version, all metadata fields are stored in the log's tag section in the format __tag__:<key> instead of being embedded in the log content.

  4. Impact on users

    • Consumer-side adaptation: Because the storage location has changed from "Content" to "Tag", you must adjust your log consumption logic. For example, you must use __tag__ to access the field when you run a query.

    • SQL query compatibility: SQL queries are automatically backward-compatible, so you do not need to modify existing queries to process logs from both versions.

More information

Global parameters

Parameter

Description

Configuration name

The name of the Logtail configuration. It must be unique within its Project. The name cannot be changed after the Logtail configuration is created.

Log topic type

Specifies how the log topic is generated. Options include Machine Group Topic, File Path Extraction, and Custom.

Advanced parameters

Optional advanced parameters for the global configuration. Create a Logtail pipeline configuration.

Input parameters

Parameter

Description

Logtail deployment mode

DaemonSet: Deploys one LoongCollector on each node of the cluster to collect logs from all containers on that node.

Sidecar: Each Pod runs a LoongCollector container to collect logs from all containers within that Pod. Log collection for different Pods is isolated.

File path type

Supports configuring a Path in Container or Host Path.

  • Path in Container: Select this option to collect text log files from within a container.

  • Host Path: Select this option to collect service logs from the cluster nodes.

File path

Specifies the log directory and file name based on the log's location on the host, such as an ECS instance.

  • If the target host is a Linux system, the log path must start with a forward slash (/). For example, /apsara/nuwa/**/app.Log.

  • If the target host is a Windows system, the log path must start with a drive letter. For example, C:\Program Files\Intel\**\*.Log.

Both directory and file names support exact matching and wildcards. See Wildcard matching. The only supported wildcards for log paths are the asterisk (*) and the question mark (?).

Log collection uses multi-level directory matching. This means Logtail finds all files that match the criteria in the specified directory and all its subdirectories. For example:

  • /apsara/nuwa/**/*.log indicates files with the .log suffix in the /apsara/nuwa directory and its recursive subdirectories.

  • /var/logs/app_*/**/*.log indicates files with the .log suffix in all directories that match the app_* format under the /var/logs directory and their recursive subdirectories.

  • /var/log/nginx/**/access* indicates files whose names start with access in the /var/log/nginx directory and its recursive subdirectories.

Max directory monitoring depth

Specifies the maximum directory depth to monitor. This is the maximum directory depth matched by the ** wildcard in the File Path. A value of 0 indicates that only the current directory is monitored.

Standard output

If you enable Stdout and Stderr, Logtail collects the container's standard output.

Standard error

If you enable Standard Error, Logtail collects the container's standard error.

Allow standard output to be collected multiple times

By default, a container's standard output can be collected by only one Logtail configuration. To collect standard output with multiple configurations, turn on the Allow File to Be Collected for Multiple Times switch.

Enable container metadata preview

Enabling Enable Container Metadata Preview lets you view container metadata after creating a Logtail configuration. This includes matched container information and full container information.

Container filtering

  • Filter conditions

Important
  • A container label is the label in the output of the docker inspect command and differs from a Kubernetes label. Obtain container labels.

  • An environment variable is configured when a container starts. Obtain container environment variables.

  • In Kubernetes scenarios, use Kubernetes-level information for container filtering, such as K8s Pod Name Regular Matching, K8s Namespace Regular Matching, K8s Container Name Regular Matching, and Kubernetes Pod Label Whitelist.

  1. In Kubernetes, namespaces and container names are mapped to the io.kubernetes.pod.namespace and io.kubernetes.container.name container labels, respectively. We recommend that you use these labels for container filtering. For example, if a Pod belongs to the backend-prod namespace and has a container named worker-server, you can collect logs from the container by setting the container label whitelist to io.kubernetes.pod.namespace : backend-prod or io.kubernetes.container.name : worker-server.

  2. If these two container labels do not meet your filtering needs, use the environment variable whitelist or blacklist for container filtering.

K8s Pod Name Regular Matching

Specifies a regular expression to match Pod names. Logs are collected from containers within the matched Pods. For example, if you set this parameter to ^(nginx-log-demo.*)$, all containers in Pods whose names start with nginx-log-demo are matched.

K8s Namespace Regular Matching

Specifies a regular expression to match namespaces. Logs are collected from containers in the matched namespaces. For example, if you set this parameter to ^(default|nginx)$, all containers in the nginx and default namespaces are matched.

K8s Container Name Regular Matching

Specifies a regular expression to match container names. The Kubernetes container name is defined in spec.containers. Logs are collected from containers that match the name. For example, if you set this parameter to ^(container-test)$, all containers named container-test are matched.

Container Label Whitelist (We recommend that you configure this parameter in a Docker environment and do not configure this parameter in a Kubernetes environment.)

Specifies the containers from which to collect logs. By default, this is empty, which means the standard output of all containers is collected. To set a container label whitelist, LabelKey is required and LabelValue is optional.

  • If LabelValue is empty, all containers with the LabelKey label are matched.

  • If LabelValue is not empty, only containers with a label that is identical to LabelKey=LabelValue are matched.

    By default, LabelValue is used for string matching. A match is successful only if the LabelValue is identical to the value of the container label. If the value starts with ^ and ends with $, regular expression matching is used. For example, if you set LabelKey to io.kubernetes.container.name and LabelValue to ^(nginx|cube)$, containers named nginx or cube are matched.

Multiple whitelist entries have a logical OR relationship. A container is matched if its label matches any of the whitelist entries.

Container Label Blacklist (We recommend that you configure this parameter in a Docker environment and do not configure this parameter in a Kubernetes environment.)

Excludes containers from log collection. By default, this is empty, which means no containers are excluded. To set a container label blacklist, LabelKey is required and LabelValue is optional.

  • If LabelValue is empty, all containers with the LabelKey label are excluded.

  • If LabelValue is not empty, only containers with a label that is identical to LabelKey=LabelValue are excluded.

    LabelValue defaults to string matching. A match occurs only if the value of LabelValue is identical to the value of the container label. If the value starts with ^ and ends with $, a regular expression match is performed. For example, if you set LabelKey to io.kubernetes.container.name and LabelValue to ^(nginx|cube)$, this matches containers named nginx or cube.

Multiple blacklist entries have a logical OR relationship. A container is excluded if its label matches any of the blacklist entries.

Environment Variable Whitelist

Specifies the containers from which to collect logs. By default, this is empty, which means the standard output of all containers is collected. To set an environment variable whitelist, EnvKey is required and EnvValue is optional.

  • If EnvValue is empty, all containers with the EnvKey environment variable are matched.

  • If EnvValue is not empty, only containers with an environment variable that is identical to EnvKey=EnvValue are matched.

    By default, EnvValue is used for string matching. A match is found only if the value of EnvValue is identical to the value of the environment variable. If the value starts with ^ and ends with $, it is a regular expression match. For example, if you set EnvKey to NGINX_SERVICE_PORT and EnvValue to ^(80|6379)$, this configuration matches containers whose service port is 80 or 6379.

Multiple whitelist entries have a logical OR relationship. A container is matched if its environment variables match any of the specified key-value pairs.

Environment Variable Blacklist

Excludes containers from log collection. By default, this is empty, which means no containers are excluded. To set an environment variable blacklist, EnvKey is required and EnvValue is optional.

  • If EnvValue is empty, logs from all containers with the EnvKey environment variable are excluded.

  • If EnvValue is not empty, only containers with an environment variable that is identical to EnvKey=EnvValue are excluded.

    By default, EnvValue is used for string matching, which means a match is successful only if the value of EnvValue is identical to the value of the environment variable. If the value starts with ^ and ends with $, it is treated as a regular expression. For example, if you set EnvKey to NGINX_SERVICE_PORT and EnvValue to ^(80|6379)$, this configuration matches containers that have a service port of 80 or 6379.

Multiple blacklist entries have a logical OR relationship. A container is excluded if its environment variables match any of the specified key-value pairs.

Kubernetes Pod Label Whitelist

Specifies the containers from which to collect logs by using a Kubernetes label whitelist. To set a Kubernetes label whitelist, LabelKey is required and LabelValue is optional.

  • If LabelValue is empty, all containers with the LabelKey Kubernetes label are matched.

  • If LabelValue is not empty, only containers with a Kubernetes label that is identical to LabelKey=LabelValue are matched.

    By default, LabelValue uses string matching, which means a match occurs only if the LabelValue is identical to the value of the Kubernetes label. If the value starts with ^ and ends with $, it is treated as a regular expression. For example, setting LabelKey to app and LabelValue to ^(test1|test2)$ matches containers that have the Kubernetes label app:test1 or app:test2.

Multiple whitelist entries have a logical OR relationship. A container is matched if its Kubernetes label matches any of the whitelist entries.

Note
  • If you change a label on a Kubernetes resource controller such as a Deployment at runtime, the running Pod is not restarted. Therefore, the Pod cannot detect the change, which may cause matching rules to fail. When you configure the Kubernetes label whitelist and blacklist, use the Kubernetes labels on the Pods. For more information about Kubernetes labels, see Labels and Selectors.

Kubernetes Pod Label Blacklist

Excludes containers from log collection by using a Kubernetes label blacklist. To set a Kubernetes label blacklist, LabelKey is required and LabelValue is optional.

  • If LabelValue is empty, all containers with the LabelKey Kubernetes label are excluded.

  • If LabelValue is not empty, only containers with a Kubernetes label that is identical to LabelKey=LabelValue are excluded.

    By default, LabelValue performs an exact string match. A match is found only if the LabelValue is identical to the value of the Kubernetes label. If the value starts with ^ and ends with $, it is treated as a regular expression. For example, if you set LabelKey to app and set LabelValue to ^(test1|test2)$, this matches containers with the Kubernetes labels app:test1 or app:test2.

Multiple blacklist entries have a logical OR relationship. A container is excluded if its Kubernetes label matches any of the blacklist entries.

Note
  • If you change a label on a Kubernetes resource controller such as a Deployment at runtime, the running Pod is not restarted. Therefore, the Pod cannot detect the change, which may cause matching rules to fail. When you configure the Kubernetes label whitelist and blacklist, use the Kubernetes labels on the Pods. For more information about Kubernetes labels, see Labels and Selectors.

Log tag enrichment

Adds environment variables and Kubernetes labels to logs as log tags.

Environment Variables

After you configure environment variable extension fields, Log Service adds fields related to environment variables to your logs. For example, if you set Environment Variable Name to VERSION and Tag Name to env_version, and a container has the environment variable VERSION=v1.0.0, the field __tag__:__env_version__: v1.0.0 is added to your logs.

Pod Labels

After you configure the Kubernetes Pod extension fields, Log Service adds Kubernetes Pod-related fields to your logs. For example, if you set the Pod Label Name to app and the Tag Name to k8s_pod_app, the field __tag__:__k8s_pod_app__: serviceA is added to the logs for a Pod that has the label app=serviceA.

File encoding

Specifies the encoding format of the log files.

First collection size

When the configuration first takes effect, this parameter specifies the starting collection position, measured from the end of the file. The default value is 1024 KB.

  • For the first collection, if a file is smaller than 1024 KB, collection starts from the beginning of the file.

  • For the first collection, if a file is larger than 1024 KB, collection starts at 1024 KB from the end of the file.

You can modify the First Collection Size. The value, specified in KB, can range from 0 to 10,485,760.

Collection blacklist

Enabling the Collection Blacklist switch lets you configure a blacklist to ignore specified directories or files during collection. You can specify directories and file names by using exact matches or wildcards. The only supported wildcards are the asterisk (*) and the question mark (?).

Important
  • If you use a wildcard in the File Path but want to filter out some of the resulting paths, you must enter the corresponding full paths in the Collection Blacklist to ensure the blacklist configuration takes effect.

    For example, if you set the File Path to /home/admin/app*/log/*.log but want to exclude all subdirectories in the /home/admin/app1* directory, select Directory Blacklist and set the directory to /home/admin/app1*/**. If you set the directory to /home/admin/app1*, the blacklist will not take effect.

  • Blacklist matching incurs computational overhead. For optimal performance, use 10 or fewer blacklist entries.

  • A directory path cannot end with a forward slash (/). For example, if you set the path to /home/admin/dir1/, the directory blacklist does not take effect.

You can configure a blacklist by file path, file name, or directory.

File Path Blacklist

  • Select File Path Blacklist and set the path to /home/admin/private*.log to ignore all files in the /home/admin/ directory that start with private and end with .log during collection.

  • Select File Path Blacklist and set the path to /home/admin/private*/*_inner.log to ignore files that end with _inner.log within directories that start with private under the /home/admin/ directory. For example, the file /home/admin/private/app_inner.log is ignored, but the file /home/admin/private/app.log is collected.

File blacklist

If you select File Blacklist and set the file name to app_inner.log, all files named app_inner.log are ignored during collection.

Directory blacklist

  • Select Directory Blacklist and set the directory to /home/admin/dir1. This ignores all files in the /home/admin/dir1 directory during collection.

  • Select Directory Blacklist and set the directory to /home/admin/dir* to ignore all files in subdirectories that start with dir under the /home/admin/ directory during collection.

  • Select Directory Blacklist and set the directory to /home/admin/*/dir. This ignores all files in any second-level subdirectory named dir under the /home/admin/ directory during collection. For example, files in the /home/admin/a/dir directory are ignored, but files in the /home/admin/a/b/dir directory are collected.

Allow file to be collected multiple times

By default, a log file can be matched by only one Logtail configuration. If the logs in a file need to be collected multiple times, turn on the Allow File to Be Collected for Multiple Times switch.

Advanced parameters

Optional advanced parameters for the file input plugin. Create a Logtail pipeline configuration.

Processor parameters

Parameter

Description

Log sample

A sample of the log you want to collect. Use a log sample from your actual use case. The sample helps you configure processing parameters more easily. You can add multiple samples. The total length cannot exceed 1,500 characters.

[2023-10-01T10:30:01,000] [INFO] java.lang.Exception: exception happened
    at TestPrintStackTrace.f(TestPrintStackTrace.java:3)
    at TestPrintStackTrace.g(TestPrintStackTrace.java:7)
    at TestPrintStackTrace.main(TestPrintStackTrace.java:16)

Multi-line mode

  • Multiline log type: A multiline log is an entry that spans multiple lines. You must define a rule to identify the start of each log entry.

    • Custom: Uses a Regex to Match First Line to identify each log entry.

    • Multi-line JSON: Each JSON object is expanded into multiple lines. Example:

      {
        "name": "John Doe",
        "age": 30,
        "address": {
          "city": "New York",
          "country": "USA"
        }
      }
  • Action on split failure:

    Exception in thread "main" java.lang.NullPointerException
        at com.example.MyClass.methodA(MyClass.java:12)
        at com.example.MyClass.methodB(MyClass.java:34)
        at com.example.MyClass.main(MyClass.java:½0)

    If Log Service fails to split the preceding log content:

    • Discard: Discards this log segment.

    • Retain Single Line: Retains each line of text as a separate log entry, resulting in four log entries in total.

Processing mode

Processors, which includes the Native Processor and the Extended Processor. For more information about processors, see Use native and extended processors.

Important

For processor usage limitations, refer to the console prompts.

  • Logtail 2.0 and later:

    • You can combine native processors in any way.

    • You can combine native and extended processors, but all extended processors must follow all native processors.

  • Logtail versions earlier than 2.0:

    • You cannot use native and extended processors together.

    • Native processors can be used only to collect text logs. When using native processors, you must meet the following requirements:

      • The first processor must be a regular expression parsing, delimiter-based parsing, JSON parsing, Nginx pattern parsing, Apache pattern parsing, or IIS pattern parsing processor.

      • After the initial parsing processor, you can add at most one time-parsing processor, one filtering processor, and multiple data-masking processors.

    • For the Retain Original Field if Parsing Fails and Retain Original Field if Parsing Succeeds parameters, only the following combinations are valid.

      • Upload only successfully parsed logs:

        image

      • Upload parsed logs on success and raw logs on failure:

        image

      • On success, upload parsed logs and append the raw log field. On failure, upload raw logs.

        For example, if the original log "content": "{"request_method":"GET", "request_time":"200"}" is parsed successfully, appending the original field adds a new field to the parsed log. The field name is the renamed original field (if left blank, the name defaults to the original field name), and the field value is the original log {"request_method":"GET", "request_time":"200"}.

        image