Docker container logs (standard output/files)

更新时间:
复制 MD 格式

In a containerized environment, application logs are often scattered across the standard output (stdout) or log files of individual Docker containers, making centralized management and quick searches challenging. LoongCollector from SLS aggregates these logs into a single Logstore, enabling centralized storage, structured parsing, data masking, filtering, and efficient query and analysis.

Requirements

  • Permission requirements: The Alibaba Cloud account or RAM user you use for deployment must have the AliyunLogFullAccess permission.

  • Docker and LoongCollector requirements:

    • If your Docker Engine version is v29.0 or later, or the minimum supported Docker API version is 1.42 or later, you must use LoongCollector 3.2.4 or later. Otherwise, LoongCollector cannot collect standard container output or file logs.

    • LoongCollector versions 3.2.4 and later support Docker API versions from 1.24 to 1.48.

    • LoongCollector versions 3.2.3 and earlier support Docker API versions from 1.18 to 1.41.

  • Limitations on collecting standard container output:

    • You must add "log-driver": "json-file" to the Docker configuration file daemon.json.

    • For CentOS 7.4 and later versions, excluding CentOS 8.0, you must set fs.may_detach_mounts=1.

  • Limitations on collecting text logs: Only the overlay and overlay2 storage drivers are supported. If you use other driver types, you must manually mount the log directory.

Collection configuration

  1. Prerequisites: Create a project and a logstore. A project is a resource management unit that isolates logs from different applications, and a logstore stores logs.

  2. Configure a machine group (install LoongCollector): Install LoongCollector on the servers from which you want to collect logs and add them to a machine group. Use the machine group to centrally manage collection nodes, distribute configurations, and monitor their status.

  3. Create and configure a log collection rule

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

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

      • Multi-line logs: This applies to single log entries that span multiple lines, such as Java exception stacks or Python tracebacks. Use a regular expression to identify the start of a line, which marks the beginning of each entry.

      • Structured parsing: Configure parsing plugins, such as regular expressions, separators, or NGINX mode, to extract structured key-value pairs from raw strings. This simplifies subsequent queries and analysis.

    3. Data Filtering: Configure a collection blacklist and content filtering rules to filter out irrelevant log content. This reduces redundant data transmission and storage.

    4. Log categorization: Configure topics and log tags to distinguish logs from different applications, containers, or source paths.

  4. Query and Analysis Configurations: A full-text index is enabled by default and supports keyword searches. We recommend that you enable a field index on structured fields for precise queries and analysis to improve search efficiency.

  5. Validation and troubleshooting: After completing the configuration, verify that logs are collected as expected. If you encounter issues such as no data being collected, heartbeat failures, or parsing errors, see FAQ.

Preparations

Before you collect logs, create a Project and a LogStore. If you already have these resources, you can skip this section and go to Step 1: Configure a machine group (install LoongCollector).

Project creation

  1. Log on to the Simple Log Service console.

  2. Click Create Project and configure the following parameters:

    • Region: Select the region that contains your log sources. You cannot change this setting after you create the Project.

    • Project Name: Enter a name for the Project. The name must be globally unique within Alibaba Cloud and cannot be changed after creation.

    • Leave the other settings at their default values and click Create. For more information, see Create a Project.

LogStore creation

  1. In the Project list, click the name of the target Project.

  2. In the left-side navigation pane, under imageLogstores, click +.

  3. On the Create LogStore page, configure the following core parameters:

    • Logstore Name: Set a name that is unique within the Project. This name cannot be changed after the LogStore is created.

    • Logstore Type: Select Standard or Query based on your requirements.

    • Billing Mode:

      • Pay-by-feature (Cannot Be Changed): This mode bills you separately for individual resources, including storage, indexing, and read/write operations. This mode is ideal for small-scale scenarios or when your feature usage is unpredictable.

      • Pay-by-ingested-data: This mode bills you only for the volume of ingested raw data. This mode provides 30 days of free storage and free features such as data processing and data shipping. It is suitable for business scenarios with a data retention period close to 30 days or complex data processing pipelines.

    • Data Retention Period: Specify the number of days to retain logs. Valid values: 1 to 3,650. A value of 3,650 indicates permanent storage. The default value is 30.

    • Leave the other settings at their default values and click OK. For more information, see Manage a LogStore.

Step 1: Configure machine group and install LoongCollector

Deploy LoongCollector as a container on the Docker host and add it to a machine group. Use the machine group to centrally manage multiple collection nodes, distribute configurations, and monitor their status.

  1. Pull the image

    On a host with Docker installed, run the following command to pull the LoongCollector image. Replace ${region_id} with the region ID of the host's region or a nearby region (such as cn-hangzhou) to improve download speed and stability.

    # LoongCollector image address
    docker pull aliyun-observability-release-registry.${region_id}.cr.aliyuncs.com/loongcollector/loongcollector:v3.0.12.0-25723a1-aliyun
    # Logtail image address
    docker pull registry.${region_id}.aliyuncs.com/log-service/logtail:v2.1.11.0-aliyun
  2. Start the LoongCollector container

    Run the following command to start the container. Make sure to correctly mount the required directories and set the required environment variables:

    docker run -d \
        -v /:/logtail_host:ro \
        -v /var/run/docker.sock:/var/run/docker.sock \
        --env ALIYUN_LOGTAIL_CONFIG=/etc/ilogtail/conf/${sls_upload_channel}/ilogtail_config.json \
        --env ALIYUN_LOGTAIL_USER_ID=${aliyun_account_id} \
        --env ALIYUN_LOGTAIL_USER_DEFINED_ID=${user_defined_id} \
        aliyun-observability-release-registry.${region_id}.cr.aliyuncs.com/loongcollector/loongcollector:v3.0.12.0-25723a1-aliyun

    Parameters:

    • ${sls_upload_channel}: The log upload channel. Set its value based on your Project's region and the desired network transfer type. For example:

      Transfer type

      Value format

      Example

      Use cases

      internal network transfer

      regionId

      cn-hangzhou

      The ECS instance and the Project are in the same region.

      internet transfer

      regionId-internet

      cn-hangzhou-internet

      • The ECS instance and the Project are in different regions.

      • The server is on another cloud platform or in a self-built data center.

      transfer acceleration

      regionId-acceleration

      cn-hangzhou-acceleration

      Cross-region communication within and outside Chinese mainland.

    • ${aliyun_account_id}: Your Alibaba Cloud account ID.

    • ${user_defined_id}: The custom identifier for the machine group, used to bind the collector to the group (for example, user-defined-docker-1). This identifier must be unique within the region.

      Important

      Requirements:

      • Correctly configure the three key environment variables:

        ALIYUN_LOGTAIL_CONFIG, ALIYUN_LOGTAIL_USER_ID, and ALIYUN_LOGTAIL_USER_DEFINED_ID.

      • Mount /var/run/docker.sock to monitor container lifecycle events.

      • Mount the root directory (/) to /logtail_host to allow access to the host file system.

  3. Verify the container status

    docker ps | grep loongcollector

    Expected output:

    6ad510001753   aliyun-observability-release-registry.cn-beijing.cr.aliyuncs.com/loongcollector/loongcollector:v3.0.12.0-25723a1-aliyun   "/usr/local/ilogtail…"   About a minute ago   Up About a minute             recursing_shirley
  4. Configure the machine group

    In the left-side navigation pane, choose Resource Group > Machine Groups. Click Create Machine Group, configure the following parameters, and then click OK:

    • Name: Enter a custom name for the machine group, such as docker-host-group.

    • Machine Group Identifier: Select Custom Identifier.

    • Custom Identifier: Enter the ${user_defined_id} that you set when starting the container. The value must be an exact match. Otherwise, the association fails.

  5. Verify heartbeat status

    Click the name of the new machine group. On the details page, check the Machine Group Status:

Step 2: Create and configure a log collection rule

Define which logs LoongCollector collects, how it parses and filters them, and then apply the configuration to your machine groups.

  1. On the image Logstores page, click the image icon next to the name of the target logstore to expand it.

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

  3. Configure the Machine Group Configurations, and then click Next:

    • Scenario: Select Docker Containers.

    • Move the machine group that you created in Step 1 from the Source Machine Group list to the Applied Machine Group list.

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

1. Global and input configuration

Before you start, make sure that you have selected a data collection template and bound a machine group. This step defines the configuration name, log source, and collection scope.

Docker 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 changed after creation. The name must meet the following conventions:

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

    • It must start and end with a lowercase letter or a digit.

input configuration

  • Enable the Stdout and Stderr and/or Standard Error switches. By default, both are enabled.

    Important

    To prevent log inconsistencies, avoid enabling standard output and standard error simultaneously.

Docker file logs

Global Configurations:

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

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

    • It must start and end with a lowercase letter or a digit.

Input Configurations:

  • File Path Type:

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

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

  • File Path: The absolute path of the log files.

    • Linux: The path must start with a forward slash (/). For example, /data/mylogs/**/*.log matches all files with the .log extension in the /data/mylogs directory and its subdirectories.

    • Windows: The path must start with a drive letter. For example, C:\Program Files\Intel\**\*.Log.

  • Maximum Directory Monitoring Depth: The maximum directory depth that the ** wildcard in the File Path can traverse. The default value is 0, which indicates the current directory only. Valid values: 0 to 1000.

    We recommend that you set this parameter to 0 and configure the path to the directory that contains the files.

2. Log processing and structuring

Configure processing rules to convert raw, unstructured logs into structured data, which improves query and analysis efficiency. We recommend that you add a log sample before you configure the rules:

On the Logtail Configuration page, in the Processor Configurations section, click Add Sample Log and enter your log content. The system identifies the log format based on the sample and helps generate regular expressions and parsing rules, which simplifies the configuration process.

Scenario 1: Process multi-line logs

By default, multi-line logs, such as Java exception stack traces, are split into separate entries, resulting in a loss of context. To prevent this, enable multi-line mode and configure a first-line regular expression to merge consecutive lines into a single, complete log entry.

Example:

Raw log

Default mode: Stack trace is broken into multiple entries

Multi-line mode: Stack trace is merged into a single entry

[2025-11-13T10:52:20,557] [ERROR] java.sql.SQLException: No suitable driver found for jdbc:mysql://db.host:3306/prod_db
    at com.datastore.util.DataProcessor.save(DataProcessor.java:434)
    at io.awesomeapp.util.PaymentGateway.fetchData(PaymentGateway.java:463)
    at org.awesomeapp.util.UserService.processRequest(UserService.java:252)
    at io.datastore.service.DatabaseConnector.fetchData(DatabaseConnector.java:172)
    at org.datastore.service.UserService.fetchData(UserService.java:517)

image

image

Configuration steps: In the Processor Configurations section of the Logtail Configuration page, 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 regular expression must match a complete line. For the example above, the expression is \[\d+-\d+-\w+:\d+:\d+,\d+]\s\[\w+]\s.*.

        • Automatic generation: Click Generate Regular Expression, select the required log content in the Log Sample text box, and then click Generate Regex.

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

    • Multi-line JSON: If all raw logs are in standard JSON format, Log Service automatically handles line breaks within a single JSON log.

  • Processing Method If Splitting Fails:

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

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

Scenario 2: Structure logs

Log Service provides various parsing plugins that convert raw logs into structured data. This provides a solid foundation for subsequent analysis, monitoring, and alerting.

Example:

Raw log

Structured log

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

Configuration steps: In the Processor Configurations section of the Logtail Configuration page:

  1. Add a parsing plugin: Click Add Processor and configure a plugin such as regular expression parsing, delimiter parsing, or JSON parsing based on your log format. For example, to collect NGINX logs, select Native Processor > Data Parsing (NGINX Mode).

  2. NGINX Log Configuration: Copy the complete 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 must be exactly the same as the one used to generate the logs.

  3. Common Parameters: The following parameters appear in multiple data parsing plugins and have consistent functions and usage.

    • Source Field: The name of the source field to parse. The default value is content, which is the entire content of the collected log.

    • Keep Source Field on Parse Failure: We recommend that you enable this option. If parsing fails due to a format mismatch, the original log content is retained in the specified source field.

    • Keep Source Field on Parse Success: Select this option to retain the original log content even if the log is successfully parsed.

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 creates data leakage risks. You can 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:

Raw log

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}

Configuration steps: In the Processor Configurations section of the Logtail Configuration page:

Click Add Processor and select Native Processor > Data Filtering:

  • Field Name: The log field to use for filtering.

  • Field Value: The regular expression to use for filtering. Only full-text matching is supported. Partial keyword matching is not supported.

Collection blacklist

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

Configuration steps: On the Logtail Configuration page, in the Input Configurations > Other Input Configurations section, enable Collection Blacklist and click Add.

Supports full path matching and wildcards (* and ?) for directory and file names.
  • File Path Blacklist: The file paths to ignore. For example:

    • /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 that end with _inner.log in directories that start with private under the /home/admin/ directory.

  • File Blacklist: The filenames to ignore during collection. For example:

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

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

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

    • /home/admin/dir*: Ignores files in all subdirectories of the /home/admin/ directory that start with dir.

    • /home/admin/*/dir: Ignores all files in subdirectories named dir at the second level of the /home/admin/ directory. For example, files in the /home/admin/a/dir directory are ignored, while files in the /home/admin/a/b/dir directory are collected.

Container filtering

Set collection conditions based on container metadata, such as environment variables, Pod labels, namespaces, or container names, to precisely control which container logs are collected.

Configuration steps: In the Input Configurations section 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 the Go RE2 engine, which has some limitations compared to engines such as PCRE. When you write regular expressions, follow the limits described in Appendix: Regular expression limits (container filtering).
  • Environment Variable Whitelist/Blacklist: Specify the environment variable conditions for the containers from which you want to collect logs.

  • K8s Pod Label Whitelist/Blacklist: Specify the label conditions for the Pods where the target containers are located.

  • K8s Pod Name Regex Match: Specify the containers to be collected by Pod name.

  • K8s Namespace Regex Match: Specify the containers to be collected by namespace name.

  • K8s Container Name Regex Match: Specify the containers to be collected by container name.

  • Container Label Whitelist/Blacklist: Collect logs from containers whose labels meet the specified conditions. This parameter is intended for Docker scenarios and is not recommended for Kubernetes scenarios.

4. Log categorization

In scenarios where multiple applications or instances share the same log format, distinguishing the log source is difficult, which reduces context during queries and impairs analysis efficiency. To address this, you can configure topics and log tags to achieve automated context association and logical categorization.

Topics

If multiple applications or instances have the same log format but different paths, such as /apps/app-A/run.log and /apps/app-B/run.log, it is difficult to distinguish the source of the collected logs. You can generate a topic based on the machine group, a custom name, or file path extraction to distinguish logs from different applications or path sources.

Configuration steps: In the Global Configurations > Other Global Configurations > Log Topic Type section, select a method to generate topics. The following three methods are supported:

  • machine group topic: If a collection configuration is applied to multiple machine groups, LoongCollector automatically uses the name of the machine group to which the server belongs as the value of the __topic__ field. Use this method to organize logs by host cluster.

  • Custom: The format is customized://<custom_topic_name>. For example, customized://app-login. Use this method for static topics with fixed application identifiers.

  • File Path Extraction: Extract key information from the full path of the log file to dynamically tag the log source. Use this method when multiple users or applications share the same log filename but have different paths.

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

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

    You can configure File Path Extraction and use a regular expression to extract key information from the full path. The matched result is uploaded to the logstore as the topic.

    Extraction rules

    The number and naming of capturing groups in the regular expression determine the output field format.

    In the regular expression for the file path, you must escape the forward slash (/).

    Capturing group type

    Use case

    Generated field

    Regex example

    Example path

    Generated field

    Single capturing group (one (.*?))

    Distinguishing sources by a single dimension (such as username or environment).

    Generates the __topic__ field.

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

    /logs/userA/app.log

    __topic__: userA

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

    Requires multiple dimensions but no semantic labels.

    Generates the tag field __tag__:__topic_{i}__, where {i} is the index of the capturing group.

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

    /logs/userA/svcA/app.log

    __tag__:__topic_1__userA;

    __tag__:__topic_2__svcA

    Multiple Capturing Groups - Naming (using (?P<name>.*?)

    Requires multiple dimensions and clear field names for easier querying and analysis.

    Generates a tag field __tag__:{name}.

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

    /logs/userA/svcA/app.log

    __tag__:user:userA;

    __tag__:service:svcA

Log tagging

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

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

  • Environment Variables: Configure an environment variable name and a tag key. The value of the environment variable is stored as the value of the tag.

    • 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 name and a tag key. The value of the Pod label is stored as the value of the tag.

    • Pod Label Name: The name 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, and the lz4 compression method is used. To distribute logs from the same source to different logstores, follow these steps:

Multi-target distribution

Important
  • LoongCollector 3.0.0 and later supports sending logs to multiple targets. Logtail does not support this feature.

  • You can configure a maximum of five output targets.

  • After you configure multiple output targets, the configuration no longer appears in the list for the current logstore. To view, modify, or delete a multi-target distribution configuration, see How do I manage multi-target distribution configurations?.

Configuration steps: In the Output Configurations section of the Logtail Configuration page:

  1. Click image to expand the output configuration.

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

    • Logstores: Select the destination logstore.

    • Compression Method: Supported methods are lz4 and zstd.

    • Route Settings: Route logs based on their tag fields. Logs that match the routing configuration are uploaded to the destination logstore. If the routing configuration is empty, all collected logs are uploaded to the destination logstore.

      • Tag Name: The name of the tag field for routing. Enter the field name directly, such as __path__, without the __tag__: prefix. Tag fields are divided into the following two types:

        For more information about tags, see Manage LoongCollector collection tags.
        • Agent-related: Tags related to the collection agent itself that do not depend on plugins. Examples include __hostname__ and __user_defined_id__.

        • Input plugin-related: Tags that are provided and enriched by the input plugin. Examples include __path__ for file collection, and _pod_name_ and _container_name_ for Kubernetes collection.

      • Tag Value: Logs with a tag value that matches this value are sent to this destination logstore.

      • Discard this tag?: If enabled, the uploaded logs will not include this tag.

Step 3: Query and analysis configuration

After configuring log processing and plug-ins, click Next to proceed to the Query and Analysis Configurations page:

  • By default, a full-text index is enabled to support keyword searches on raw log content.

  • To run precise, field-based queries, click Automatic Index Generation after the Preview Data loads. SLS then creates a field index from the first previewed log entry.

Complete the configuration and click Next to finish the collection setup.

Step 4: Validate and troubleshoot

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

View uploaded logs

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

  2. Query logs: Go to the Search & Analyze page of the target logstore and click Search & Analyze. The default time range is the last 15 minutes. Check for incoming logs. By default, collected Docker container text logs include the following fields:

    Parameter

    Description

    __source__

    The IP address of the LoongCollector (Logtail) container.

    _container_ip_

    The IP address of the application container.

    __tag__:__hostname__

    The name of the Docker host where LoongCollector (Logtail) is running.

    __tag__:__path__

    The log collection path.

    __tag__:__receive_time__

    The time when the server received the log.

    __tag__:__user_defined_id__

    The custom ID of the machine group.

Troubleshooting

Machine group heartbeat is FAIL

  1. Check the user ID: If your server is not an ECS instance, or if the ECS instance and the project belong to different Alibaba Cloud accounts, verify that the correct user ID file exists in the specified directory.

    • Linux: Run the cd /etc/ilogtail/users/ && touch <uid> command to create a user ID file.

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

    If a file exists in the specified path and its name matches the Alibaba Cloud account ID of the current project, the user ID is configured correctly.

  2. Check the machine group identifier: If you use a custom ID for your machine group, check whether a user_defined_id file exists in the specified directory. If the file exists, verify that its content is consistent with the custom ID configured for the machine group.

    System

    Specified directory

    Solution

    Linux

    /etc/ilogtail/user_defined_id

    # Configure the custom ID. If the directory does not exist, create it manually.
    echo "user-defined-1" > /etc/ilogtail/user_defined_id

    Windows

    C:\LogtailData\user_defined_id

    In the C:\LogtailData directory, create a file named user_defined_id and write the custom ID to it. If the directory does not exist, create it manually.

  3. If both the user ID and the machine group identifier are configured correctly, see Troubleshoot LoongCollector (Logtail) machine group issues for further troubleshooting.


No data is collected

  1. Check for incremental logs: LoongCollector starts collecting data from a file only after new log entries are written to it.

  2. Check the machine group heartbeat status: Go to the Resource Group > Machine Groups page and click the name of the target machine group. Then, in the Machine Group Configurations > Machine Group Status section, check the Heartbeat status.

  3. Verify that the LoongCollector (Logtail) collection configuration is applied to the machine group.

    1. Go to the Resource Group > Machine Groups page, click the name of the target machine group to go to the Machine Group Configurations page.

    2. Click Manage Configuration. This page displays the All Logtail Configurations list on the left and the Applied Logtail Configs list on the right. If the target LoongCollector (Logtail) configuration is in the right-side list, it is successfully applied to the machine group.

    3. If the target configuration is not in the applied list, click Modify. In the All Logtail Configurations list, select the target configuration, click the image icon to move it to the Applied Logtail Configurations list, and then click OK.


Log collection errors or incorrect format

This issue indicates that the network connection and basic configuration are correct. The problem is likely a mismatch between the log content and the parsing rules. Check the specific error message to diagnose the issue:

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

  2. In the area, check the error type of the log and see Common error types in data collection for a solution.

Next steps

  1. Log query and analysis: Automatically generate query and analysis statements with the built-in AI-powered generation of query and analysis statements (Copilot).

  2. Data visualization: Monitor key metric trends with visualization dashboards.

  3. Automatic alerting for data anomalies: Set up alert policies to detect data anomalies.

Common commands

View LoongCollector (Logtail) status

docker exec ${logtail_container_id} /etc/init.d/ilogtaild status

View LoongCollector (Logtail) information

docker exec ${logtail_container_id} cat /usr/local/ilogtail/app_info.json

View LoongCollector (Logtail) running logs

The running logs for LoongCollector (Logtail) are stored in the /usr/local/ilogtail/ directory within the container. The primary log files are loongcollector.LOG and ilogtail.LOG. Rotated log files are compressed into files such as ilogtail.LOG.x.gz. For example:

# View LoongCollector running logs
docker exec a287de895e40 tail -n 5 /usr/local/ilogtail/loongcollector.LOG
# View Logtail running logs
docker exec a287de895e40 tail -n 5 /usr/local/ilogtail/ilogtail.LOG

The output is similar to the following:

[2025-08-25 09:17:44.610496]    [info]  [22]    /build/loongcollector/file_server/polling/PollingModify.cpp:75          polling modify resume:succeeded
[2025-08-25 09:17:44.610497]    [info]  [22]    /build/loongcollector/file_server/polling/PollingDirFile.cpp:100                polling discovery resume:starts
[2025-08-25 09:17:44.610498]    [info]  [22]    /build/loongcollector/file_server/polling/PollingDirFile.cpp:103                polling discovery resume:succeeded
[2025-08-25 09:17:44.610499]    [info]  [22]    /build/loongcollector/file_server/FileServer.cpp:117            file server resume:succeeded
[2025-08-25 09:17:44.610500]    [info]  [22]    /build/loongcollector/file_server/EventDispatcher.cpp:1019              checkpoint dump:succeeded

Restart LoongCollector (Logtail)

# Stop LoongCollector
docker exec a287de895e40 /etc/init.d/ilogtaild stop
# Start LoongCollector
docker exec a287de895e40 /etc/init.d/ilogtaild start

FAQ

Common error messages

Symptom

Cause

Resolution

Failed to connect to Logtail

The Project's region does not match the region of the LoongCollector (Logtail) container.

Check the region configuration in ALIYUN_LOGTAIL_CONFIG.

No logs in Logstore

The file path is misconfigured.

Verify that the log path in the application container matches the collection configuration.


The parameter is invalid: uuid=none

Problem description: The LoongCollector (Logtail) log file (/usr/local/ilogtail/ilogtail.LOG) contains the error message The parameter is invalid : uuid=none.

Resolution: On the host, create a file named product_uuid, enter a valid UUID (for example, 169E98C9-ABC0-4A92-B1D2-AA6239C0D261), and then mount this file to the /sys/class/dmi/id/product_uuid directory in the LoongCollector (Logtail) container.


Multiple collection configurations for a single source

By default, to prevent data duplication, Simple Log Service restricts each log source to a single collection configuration:

  • A text log file can be processed by only one Logtail collection configuration.

  • For container standard output (stdout):

    • With the new standard output template, logs can be collected by only one collection configuration by default.

    • The old standard output template supports collection by multiple configurations by default, without extra configuration.

  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 it.

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

  5. On the Logtail configuration page, click Edit and scroll down 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.


Multi-target distribution configurations

Because multi-target distribution configurations are associated with multiple Logstores, you must manage them from the Project-level configuration page:

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

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

    Note

    This page lists all collection configurations in the Project, including configurations for Logstores that were accidentally deleted.

Appendix: Native parsing processors

On the Logtail Configuration page, in the Processor Configurations section, you can add processors to structure raw logs. To add a processor to an existing collection configuration:

  1. In the left-side navigation pane, choose imageLogstore, and find the target Logstore.

  2. Click the image icon next to its name to expand the Logstore.

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

  4. On the Logtail Configuration page, click Edit.

This section describes common processors that cover typical log processing scenarios. For more features, see Extension Processors.
Important

Rules for combining processors (applies to LoongCollector / Logtail 2.0 and later):

  • You can use Native Processors and Extension Processors independently or combine them as needed.

  • For better performance and stability, prioritize Native Processors.

  • If native features cannot meet your business needs, you can add Extension Processors after the configured Native Processors for additional processing.

Order Constraint:

All processors form a processing chain and execute in their configured order. Note: All Native Processors must precede any Extension Processors. After you add an Extension Processor, you can no longer add any Native Processors.

Regex parsing

Extracts log fields with regular expressions and parses logs into key-value pairs. Each field can be queried and analyzed independently.

Example:

Raw log

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

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

  • Regular Expression: A regular expression for matching logs. You can generate it automatically or enter it manually.

    • Automatic generation:

      • Click Automatically Generate Regular Expression.

      • In the Log Sample section, highlight the log content to extract.

      • Click Generate Regular Expression.

        Paste a correctly formatted log, such as an Apache Combined access log, into the Log Sample field. Then, click Generate Regular Expression to automatically generate the parsing expression.

    • Manual input: Enter a regular expression based on the log format.

    After you complete the configuration, click Validate to test whether the regular expression correctly parses the log content.

  • Extracted Field: Set the field names (Keys) for the extracted log content (Values).

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


Delimiter parsing

Splits log content using a delimiter and parses the content into multiple key-value pairs. This feature supports single-character and multi-character delimiters.

Example:

Raw log

Split a field by the, character

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 section, click Add Processor, and select Native Processor > Data Parsing (Delimiter Mode):

  • Delimiter: Specify the character used to split the log content.

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

  • Quote: If a field value contains the delimiter, you must specify a quote character to enclose the field to prevent incorrect splitting.

  • Extracted Field: Set the field name (Key) for each column in the order they are split. The field names must meet the following requirements:

    • 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.


JSON parsing

Parses a JSON log into key-value pairs.

Example:

Raw log

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

Parses a nested JSON log into key-value pairs by specifying an expansion depth.

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, for example, content.

  • JSON Expansion Depth: Specifies the recursion depth for expansion. A value of 0 (the default) expands all nested levels. A value of 1 prevents any expansion, keeping the original JSON object as the value.

  • Character to Concatenate Expanded Keys: The character used to concatenate field names during JSON expansion. The default is an underscore (_).

  • Name Prefix of Expanded Keys: The prefix for field names after JSON expansion.

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

    Example: {"k":["a","b"]} is expanded to {"k[0]":"a","k[1]":"b"}.

    To rename an expanded field, for example, from prefix_s_key_k1 to new_field_name, you can add a Rename Fields processor to complete the mapping.
  • 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 JSON objects from a JSON array.

Example:

Raw log

Result

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

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

Example: Extract elements from the JSON array in the content log field and store the results in the new json1 and json2 fields.

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

Apache log parsing

Parses log content based on the definitions in an Apache log configuration file and parses it into multiple key-value pairs.

Example:

Raw log

Parsing the Apache combined log format

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 defined in your server's Apache configuration file, which is typically located at /etc/apache2/apache2.conf.

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


Data masking

Masks sensitive data in logs.

Example:

Raw log

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 original field that contains the log content before parsing.

  • Data Masking Method:

    • const: Replaces sensitive content with a specified string.

    • md5: Replaces sensitive content with its MD5 hash.

  • Replacement String: If you set Data Masking Method to const, you must enter a string to replace the sensitive content.

  • Content Expression that Precedes Replaced Content: An expression used to locate sensitive content. Configure this parameter using the RE2 syntax.

  • Content Expression to Match Replaced Content: The expression for the sensitive content. Configure this parameter using the RE2 syntax.


Time parsing

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

Example:

Raw log

Result

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

Parses the time value from the timestamp field and sets the log's __time__ field to its Unix timestamp equivalent, 1758625907, which represents 2025-09-23T19:11:47+0800.

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

  • Original Field: The original field that contains the log content before parsing.

  • Time Format: Specify the time format that matches the time value in the log.

  • Time Zone: Select the time zone of the log's time field. By default, this is the time zone of the machine where LoongCollector (or Logtail) is running.

Appendix: Regular expression limitations (container filtering)

The regular expressions used for container filtering are based on Go's RE2 engine, which has some syntax limitations compared to other engines like PCRE.

1. Differences in named group syntax

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

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

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

2. Unsupported regex features

RE2 does not support the following common but complex regex features:

  • Lookarounds: (?=...), (?!...), (?<=...), (?<!...)

  • Conditionals: (?(condition)true|false)

  • Recursion: (?R), (?0)

  • Subroutine calls: (?&name), (?P>name)

  • Atomic groups: (?>...)

3. Usage recommendations

When debugging regular expressions with a tool like Regex101, select the Golang (RE2) flavor to validate them and ensure compatibility. If you use any unsupported syntax, the plugin cannot parse or match your expression correctly.

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

Regions

  1. Log on to the Simple Log Service console. In the project list, click the destination project.

  2. Click the image icon next to the project name to go to the project overview page.

  3. In the Basic Information section, view the region name of the current project. The following table maps region names to their corresponding Region IDs.

    A region is the geographical location of the physical data center for a cloud service. A Region ID is the unique identifier of a cloud service region.

    Region name

    Region ID

    China (Qingdao)

    cn-qingdao

    China (Beijing)

    cn-beijing

    China (Zhangjiakou)

    cn-zhangjiakou

    China (Hohhot)

    cn-huhehaote

    China (Ulanqab)

    cn-wulanchabu

    China (Hangzhou)

    cn-hangzhou

    China (Shanghai)

    cn-shanghai

    China (Nanjing - Local Region - Decommissioning)

    cn-nanjing

    China (Fuzhou - Local Region - Decommissioning)

    cn-fuzhou

    China (Shenzhen)

    cn-shenzhen

    China (Heyuan)

    cn-heyuan

    China (Guangzhou)

    cn-guangzhou

    Philippines (Manila)

    ap-southeast-6

    South Korea (Seoul)

    ap-northeast-2

    Malaysia (Kuala Lumpur)

    ap-southeast-3

    Japan (Tokyo)

    ap-northeast-1

    Thailand (Bangkok)

    ap-southeast-7

    China (Chengdu)

    cn-chengdu

    Singapore

    ap-southeast-1

    Indonesia (Jakarta)

    ap-southeast-5

    China (Hong Kong)

    cn-hongkong

    Germany (Frankfurt)

    eu-central-1

    US (Virginia)

    us-east-1

    US (Silicon Valley)

    us-west-1

    UK (London)

    eu-west-1

    UAE (Dubai)

    me-east-1

    SAU (Riyadh - Partner Region)

    me-central-1

Network transmission types

Network type

Domain type

Description

Use cases

Alibaba Cloud internal network

Private domain name

The Alibaba Cloud internal network is a gigabit shared network that provides faster and more stable data transfer than the internet. The internal network includes VPCs and classic networks.

The ECS instance and the Simple Log Service (SLS) Project are in the same region, or a server is connected to a VPC through Express Connect.

Note

For optimal performance and to avoid internet charges, create your SLS Project in the same region as your ECS instance to collect logs over the Alibaba Cloud internal network.

Internet

Public domain name

Transferring log data over the internet is limited by network bandwidth. The speed and stability of data collection can also be affected by network jitter, latency, and packet loss.

Use the internet for data transfer in the following scenarios:

  • The ECS instance and the SLS Project are in different regions.

  • The server is hosted by another cloud provider or in a self-managed data center.

Transfer acceleration

acceleration endpoint

This method accelerates log collection by using Alibaba Cloud CDN edge nodes. It improves network latency and stability compared to the internet but incurs additional traffic fees.

Use transfer acceleration when high latency or instability occurs during cross-region data transfer over the internet, for example, between domestic and international regions. For more information, see Transfer acceleration.