All Products
Search
Document Center

Simple Log Service:Collect Kubernetes pod text logs (sidecar mode)

Last Updated:Oct 10, 2026

Sidecar mode injects a dedicated LoongCollector (Logtail) container into each application pod for per-pod log collection. It is ideal when you need fine-grained control, multi-tenant isolation, or lifecycle-bound log collection.

How it works

In sidecar mode, the application container and a LoongCollector (Logtail) container run side-by-side in a pod, sharing volumes for log access and lifecycle synchronization.

  • Log sharing: The application container writes logs to a shared volume (typically an emptyDir), which the LoongCollector (Logtail) container mounts read-only to collect in real time.

  • Configuration association: Each LoongCollector (Logtail) sidecar declares its identity through a unique custom identifier. A machine group in the SLS console with the same identifier distributes collection configurations to all matching sidecars.

  • Lifecycle synchronization: Signal files (cornerstone and tombstone) in the shared volume coordinate container shutdown. Together with the graceful termination period (terminationGracePeriodSeconds), they ensure LoongCollector (Logtail) finishes sending remaining logs before the pod exits.

Before you begin

Create a Project and a LogStore to store your logs. If you already have them, skip to Step 1: Inject the LoongCollector Sidecar Container.

  • Project: A resource management unit in SLS that isolates logs by project or service.

  • LogStore: A storage unit for logs.

Create a project

  1. Log in to the Simple Log Service console.

  2. Click Create Project and configure the following settings:

    • Region: Select the region of your log source. Cannot be changed after creation.

    • Project Name: Must be globally unique within Alibaba Cloud. Cannot be changed after creation.

    • Leave the other parameters at their default settings and click Create. Other parameters are described in Create Project.

Create a LogStore

  1. Click the name of your Project.

  2. In the left-side navigation pane, choose imageLog Storage, and then click +.

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

    • Logstore Name: Must be unique within the Project. Cannot be changed after creation.

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

    • Billing Mode:

      • Pay-by-feature: Billed independently for storage, indexing, and read/write operations. Ideal for small-scale or unpredictable usage.

      • Pay-by-ingested-data: Billed only for raw data ingested. Includes 30 days of free storage and free data processing and shipping. Ideal when retention is around 30 days or pipelines are complex.

    • Data Retention Period: Log retention in days. Range: 1 to 3,650 (3,650 = permanent). Default: 30.

    • Leave the other parameters at their default settings and click OK. Other parameters are described in Manage LogStore.

Step 1: Inject the LoongCollector sidecar container

Inject a LoongCollector sidecar container into your application pod with a shared volume for log collection. For a quick test, use the Appendix: YAML example.

1. Modify the pod YAML configuration

  1. Define shared volumes

    In spec.template.spec.volumes, add three shared volumes at the same level as containers:

    volumes:
      # Shared log directory (written by the application container, read by the sidecar)
      - name: ${shared_volume_name} # <-- The name must match the name in volumeMounts
        emptyDir: {}
      # Signal directory for inter-container communication (for graceful start/stop)
      - name: tasksite
        emptyDir:
          medium: Memory  # Use memory as the medium for better performance
          sizeLimit: "50Mi"
      # Shared host time zone configuration: Synchronizes the time zone for all containers in the pod
      - name: tz-config # <-- The name must match the name in volumeMounts
        hostPath:
          path: /usr/share/zoneinfo/Asia/Shanghai  # Modify the time zone as needed
    
  2. Configure application container mounts

    In the volumeMounts section of your application container, such as your-business-app-container, add the following volume mounts:

    Ensure that the application container writes logs to the ${shared_volume_path} directory so that LoongCollector can collect them.
    volumeMounts:
      # Mount the shared log volume to the application log output directory
      - name: ${shared_volume_name}
        mountPath: ${shared_volume_path}  # Example: /var/log/app
      # Mount the communication directory
      - name: tasksite
        mountPath: /tasksite  # Shared directory for communication with the LoongCollector container
      # Mount the timezone file
      - name: tz-config
        mountPath: /etc/localtime
        readOnly: true
    
  3. Inject the LoongCollector sidecar container

    In the spec.template.spec.containers array, append the following sidecar container definition:

    - name: loongcollector
      image: aliyun-observability-release-registry.cn-shenzhen.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
      command: ["/bin/bash", "-c"]
      args:
        - |
          echo "[$(date)] LoongCollector: Starting initialization"
          # Start the LoongCollector service
          /etc/init.d/loongcollectord start
          # Wait for the configuration to download and the service to be ready
          sleep 15
          # Verify the service status
          if /etc/init.d/loongcollectord status; then
            echo "[$(date)] LoongCollector: Service started successfully"
            touch /tasksite/cornerstone
          else
            echo "[$(date)] LoongCollector: Failed to start service"
            exit 1
          fi
          # Wait for the application container to complete (via the tombstone file signal)
          echo "[$(date)] LoongCollector: Waiting for application container to complete"
          until [[ -f /tasksite/tombstone ]]; do
            sleep 2
          done
          # Allow time to upload remaining logs
          echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
          sleep 30
          # Stop the service
          echo "[$(date)] LoongCollector: Stopping service"
          /etc/init.d/loongcollectord stop
          echo "[$(date)] LoongCollector: Shutdown complete"
      # health check
      livenessProbe:
        exec:
          command: ["/etc/init.d/loongcollectord", "status"]
        initialDelaySeconds: 30
        periodSeconds: 10
        timeoutSeconds: 5
        failureThreshold: 3
      # resource configuration
      resources:
        requests:
          cpu: "100m"
          memory: "128Mi"
        limits:
          cpu: "2000m"
          memory: "2048Mi"
      # environment variable configuration
      env:
        - name: ALIYUN_LOGTAIL_USER_ID
          value: "${your_aliyun_user_id}"
        - name: ALIYUN_LOGTAIL_USER_DEFINED_ID
          value: "${your_machine_group_user_defined_id}"
        - name: ALIYUN_LOGTAIL_CONFIG
          value: "/etc/ilogtail/conf/${your_region_config}/ilogtail_config.json"
        # Enable full drain mode to ensure all logs are sent before the pod terminates
        - name: enable_full_drain_mode
          value: "true"  
        # Append pod environment information as log tags
        - name: ALIYUN_LOG_ENV_TAGS
          value: "_pod_name_|_pod_ip_|_namespace_|_node_name_|_node_ip_"
        # Automatically inject pod and node metadata as log tags
        - name: "_pod_name_"
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: "_pod_ip_"
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: "_namespace_"
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: "_node_name_"
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: "_node_ip_"
          valueFrom:
            fieldRef:
              fieldPath: status.hostIP
      # Volume mounts (shared with the application container)
      volumeMounts:
        # Read-only mount for the application log directory
        - name: ${shared_volume_name} # <-- Shared log directory name
          mountPath: ${dir_containing_your_files} # <-- Path to the shared directory in the sidecar
          readOnly: true
        # Mount the communication directory
        - name: tasksite
          mountPath: /tasksite
        # Mount the timezone
        - name: tz-config
          mountPath: /etc/localtime
          readOnly: true
    

2. Adapt the application container lifecycle logic

Depending on the workload type, modify the application container to support a coordinated exit with the sidecar:

Short-lived tasks (Job/CronJob)

# 1. Wait for LoongCollector to be ready
echo "[$(date)] Application: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do
  sleep 1
done
echo "[$(date)] Application: LoongCollector is ready, starting application logic"
# 2. Execute core application logic (ensure logs are written to the shared directory)
echo "Hello, World!" >> /app/logs/business.log
# 3. Save the exit code
retcode=$?
echo "[$(date)] Application: Task completed with exit code: $retcode"
# 4. Notify LoongCollector that the application task is complete
touch /tasksite/tombstone
echo "[$(date)] Application: Tombstone created, exiting"
exit $retcode

Long-lived services (Deployment / StatefulSet)

# Define the signal handler function
_term_handler() {
    echo "[$(date)] [nginx-demo] Caught SIGTERM, starting graceful shutdown..."
    # Send a QUIT signal to Nginx for a graceful stop
    if [ -n "$NGINX_PID" ]; then
        kill -QUIT "$NGINX_PID" 2>/dev/null || true
        echo "[$(date)] [nginx-demo] Sent SIGQUIT to Nginx PID: $NGINX_PID"
        # Wait for Nginx to stop gracefully
        wait "$NGINX_PID"
        EXIT_CODE=$?
        echo "[$(date)] [nginx-demo] Nginx stopped with exit code: $EXIT_CODE"
    fi
    # Notify LoongCollector that the application container has stopped
    echo "[$(date)] [nginx-demo] Writing tombstone file"
    touch /tasksite/tombstone
    exit $EXIT_CODE
}
# Register the signal handler
trap _term_handler SIGTERM SIGINT SIGQUIT
# Wait for LoongCollector to be ready
echo "[$(date)] [nginx-demo]: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do 
    sleep 1
done
echo "[$(date)] [nginx-demo]: LoongCollector is ready, starting application logic"
# Start Nginx
echo "[$(date)] [nginx-demo] Starting Nginx..."
nginx -g 'daemon off;' &
NGINX_PID=$!
echo "[$(date)] [nginx-demo] Nginx started with PID: $NGINX_PID"
# Wait for the Nginx process
wait $NGINX_PID
EXIT_CODE=$?
# Also notify LoongCollector if the exit was not caused by a signal
if [ ! -f /tasksite/tombstone ]; then
    echo "[$(date)] [nginx-demo] Unexpected exit, writing tombstone"
    touch /tasksite/tombstone
fi
exit $EXIT_CODE

3. Set the termination grace period

In spec.template.spec, set a termination grace period that is long enough to allow LoongCollector to upload all remaining logs.

spec:
  # ... Your other existing spec configurations ...
  template:
    spec:
      terminationGracePeriodSeconds: 600  # 10-minute graceful stop period

4. Variables

Parameter

Description

${your_aliyun_user_id}

The ID of your Alibaba Cloud account. Configure user identifiers.

${your_machine_group_user_defined_id}

A custom identifier used to create a machine group. Example: nginx-log-sidecar.

Important

Ensure that this identifier is unique within the Project's region.

${your_region_config}

The configuration that corresponds to your SLS Project's region and network access type. Service regions.

Example: If your Project is in the China (Hangzhou) region, use cn-hangzhou for Alibaba Cloud internal network access or cn-hangzhou-internet for public network access.

${shared_volume_name}

A custom name for the shared volume.

Important

The name in volumeMounts must match the name in volumes. This ensures both containers mount the same shared volume.

${dir_containing_your_files}

The mount path in the LoongCollector container where the text logs are located.

5. Apply configuration and verify

  1. Run the following command to deploy the changes:

    kubectl apply -f <YOUR-YAML>
  2. Check the pod status to confirm that the LoongCollector container was injected successfully:

    kubectl describe pod <YOUR-POD-NAME>

    If you see two containers (the application container and loongcollector) and their status is Running, the injection is successful.

Step 2: Create a custom-identifier machine group

Registers LoongCollector sidecar instances with SLS for centralized collection configuration management.

Procedure

  1. Create a machine group

    1. Go to the target project. In the left-side navigation pane, click imageResources > Machine Groups.

    2. On the Machine Groups page, click Machine group icon > Create Machine Group.

  2. Configure the machine group

    Configure the following parameters and click OK:

    • Name: The name of the machine group. Cannot be changed after creation. The name must meet the following requirements:

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

      • Start and end with a lowercase letter or a digit.

      • Be 2 to 128 characters long.

    • Machine Group Identifier: Select Custom Identifier.

    • Custom Identifier: Enter the value of the ALIYUN_LOGTAIL_USER_DEFINED_ID environment variable that you set for the LoongCollector container in the YAML file in Step 1. The value must match exactly. Otherwise, the association will fail.

  3. Check the machine group heartbeat status

    After creating the machine group, click its name to check the heartbeat status in the Machine Group Status section.

    • OK: LoongCollector has connected to SLS, and the machine group is registered.

    • FAIL:

      • The configuration change may take up to two minutes to take effect. Refresh the page and check the status again.

      • If the status is still FAIL after two minutes, see Troubleshoot Logtail machine group issues.

Each pod corresponds to a separate LoongCollector instance. For fine-grained management, use different custom identifiers for different applications or environments.

Step 3: Create a collection configuration

A collection configuration defines which log files LoongCollector collects, how to parse them, and which content to filter.

Procedure

  1. On the image LogStore page, click the image before the target LogStore name to expand.

  2. Click image next to Data Collection. In the Quick Data Import dialog box, find the Kubernetes - File card and click Integrate Now.

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

    • Scenario: Select Kubernetes Clusters.

    • Deployment Method: Select Sidecar.

    • Select Machine Group: In the Source Machine Group list, select the machine group you created in Step 2. Click image to move it to the Applied Machine Group list.

  4. On the Logtail Configurations page, configure the Logtail collection rules.

1. Global and input configurations

Define the name, log source, and collection scope for the collection configuration.

Global Configurations:

  • Configuration Name: A custom name for the collection configuration. It must be unique within its project. The name cannot be changed 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:

  • Type: Select Text Log Collection.

  • Logtail Deployment Mode: Select Sidecar.

  • File Path Type:

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

    • Host Path: Collect local service logs from the host.

    • dockerFile: If the log files you want to collect are located inside a container (see the container path option above), you must set dockerFile: true for the collection configuration. Otherwise, Logtail processes the configuration as a regular file collection and cannot detect log files inside the container, which results in missing logs.

      • Console: In Advanced Options, select container file collection. Alternatively, the console also provides a separate Docker File - Container data collection entry point.

      • CRD: Set dockerFile: true under inputDetail.

  • File Path: The path for log collection.

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

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

  • Maximum Directory Monitoring Depth: Specifies the maximum directory depth for the ** wildcard in the File Path. The default value of 0 monitors only the current directory.

  • dockerFile: Specifies whether the target file is located inside a container. When you collect log files from within a container in Sidecar mode, you must set this parameter to true. Otherwise, the file is collected as a regular host file, which does not match the expected collection behavior. Type: Boolean. Required: No. Default value: false.

2. Log processing and structuring

Configure log processing rules to transform raw, unstructured logs into structured, searchable data. This improves the efficiency of log queries and analysis. We recommend that you add a log sample before you configure the rules:

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

Scenario 1: Handle multi-line logs (such as Java stack traces)

Logs such as Java exception stacks and JSON objects often span multiple lines. In the default collection mode, they are split into multiple incomplete records, which causes a loss of context. To prevent this, you can enable multi-line mode and configure a start-of-line regular expression to merge consecutive lines of the same log into a single, complete entry.

Example:

Raw log without any processing

In default collection mode, each line is treated as an independent log. The stack trace is broken up, and context is lost.

With multi-line mode enabled, a start-of-line regular expression identifies complete logs, preserving the full semantic structure.

2025-11-13 10:52:20.557 ERROR [app-thread-0] --- 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)

In default mode, this log is split into 6 independent records: the first contains only the java.sql.SQLException error message, while the remaining 5 stack frames (such as at com.datastore.util.DataProcessor.save(...)) are stored as separate entries. The stack frames cannot be correlated with the original exception through queries, requiring manual effort to reconstruct the context for troubleshooting.

After multi-line mode is enabled, the java.sql.SQLException: No suitable driver found for jdbc:mysql://db.host:3306/prod_db error log along with 5 stack frames (DataProcessor.save → UserService.fetchData) is collected as a single record in the log query service. The metadata column also shows IP, hostname, log path, and other fields.

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

  • Type: Select Custom or Multi-line JSON.

    • Custom: The format of the raw log 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 it automatically or enter it manually. The regular expression must match a complete line of data. For example, the matching regular expression in the preceding example is \[\d+-\d+-\w+:\d+:\d+,\d+]\s\[\w+]\s.*.

        • Automatic generation: Click Generate Regex Automatically. Then, in the Log Sample text box, select the log content to extract and click Generate Regex.

          The legacy Kubernetes standard output collection mode does not support the Add Log Sample and automatic regular expression generation features. To test a regular expression, create a LogStore of the text log type, test the regular expression in the LogStore, and then paste the regular expression into the Logtail configuration of the target LogStore.

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

    • Multi-line JSON: When all raw logs are in standard JSON format, Simple 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 start-of-line rule, it is discarded.

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

Scenario 2: Structured logs

When raw logs are unstructured or semi-structured text, such as NGINX access logs or application output logs, direct querying and analysis are often inefficient. Simple Log Service provides various data parsing plug-ins that can automatically convert raw logs of different formats into structured data. This provides a solid foundation for subsequent analysis, monitoring, and alerting.

Example:

Raw log without any processing

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

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

  1. Add a parsing plugin: Click Add Processor, and configure a plugin such as a regular expression, delimiter, or JSON parsing plugin based on your log format. For example, to collect NGINX logs, 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 must exactly match the log_format on your server. Otherwise, parsing will fail.

  3. General configuration parameter descriptions: The following parameters are common to many parsing plugins and have consistent functions.

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

    • Retain Original Field if Parsing Fails: Recommended. If the plugin fails to parse a log, this option retains the raw log content in the original field.

    • Retain Original Field if Parsing Succeeds: If selected, this option retains the raw log content even after successful parsing.

3. Log filtering

Large volumes of low-value logs (such as DEBUG or INFO level) waste storage, increase costs, reduce query efficiency, and pose data leakage risks. Configure filtering policies for efficient and secure log collection.

Content filtering

You can filter based on log content fields, such as collecting only logs with a level of WARNING or ERROR.

Example:

Raw log without any processing

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.

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

Collection blacklist

You can use a blacklist to exclude specified directories or files, which prevents irrelevant or sensitive logs from being uploaded.

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

Supports full matching and wildcard matching for directories and filenames. Only the asterisk (*) and question mark (?) wildcard characters are supported.
  • 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" in directories 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 files in all subdirectories under /home/admin/ that start with "dir".

    • /home/admin/*/dir: Ignores all files in subdirectories named "dir" at the second level under 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 (environment variables, Pod labels, namespaces, container names) to control which containers' logs are collected.

Configuration steps: On the Logtail Configurations page, in the Input Configurations area, enable Container Filtering and click Add.

Multiple conditions have an "AND" relationship. All regular expression matching is based on Go's RE2 regular expression engine, which has some limitations compared to engines such as PCRE. Follow the guidelines in Appendix: Regular expression limits (container filtering) when you write regular expressions.
  • Environment variable blacklist/whitelist: Filter containers based on their environment variables.

  • K8s Pod label blacklist/whitelist: Filter containers based on the Pod labels of their host pods.

  • K8s Pod name regex match: Filter containers based on their Pod name.

  • K8s Namespace regex match: Filter containers based on their namespace.

  • K8s container name regex match: Filter containers based on their name.

  • Container label blacklist/whitelist: Filter containers based on their labels. This method is intended for Docker and is not recommended for Kubernetes.

4. Log classification

When multiple applications share the same log format, distinguishing log sources can be difficult. Configure log topics and log tagging to automate context association and logical classification.

Log topics

When multiple applications have logs with the same format but different paths (such as /apps/app-A/run.log and /apps/app-B/run.log), generate a topic to differentiate logs from each service.

Procedure: In Global Configurations > Other Global Configurations > Log Topic Type, select a method for generating topics. The following three types are supported:

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

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

  • File path extraction: Extract key information from the full path of the log file to dynamically mark the log source. This is suitable for situations where 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 but the sub-paths and filenames are the same, 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 topic.

    File path extraction rule: Based on regular expression capturing groups

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

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

    Capturing group type

    Scenario

    Generated field

    Regex example

    Matching path example

    Generated field example

    Single capturing group (only one (.*?))

    Only one dimension is needed to distinguish the source (such as username, environment)

    Generates the __topic__ field

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

    /logs/userA/app.log

    __topic__: userA

    Multiple non-named capturing groups (multiple (.*?))

    Multiple dimensions are needed to distinguish the source, but no semantic tags are required

    Generates a tag field __tag__:__topic_{i}__, where {i} is the ordinal number of the capturing group

    \/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 to distinguish the source, and you want the field meanings to be clear for easy 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 as tags for fine-grained log grouping.

Configuration steps: In the Input Configurations area of the Logtail Configurations page, enable Log Tag Enrichment and click Add.

  • Environment Variables: Configure the environment variable name and the tag name. 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 Name: The name of the tag.

  • Pod Labels: Configure the Pod label name and the tag name. 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 Name: The name of the tag.

5. Output configuration

By default, all logs are sent to the current LogStore with lz4 compression. To distribute logs to multiple LogStores, configure additional output destinations.

Dynamic multi-destination distribution

Important
  • Multi-destination 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, the collection configuration no longer appears in the list of collection configurations for the current LogStore. To view, modify, or delete a multi-destination distribution configuration, see Manage multi-destination distribution configurations.

Configuration steps: In the Output Configurations area of the Logtail Configurations page.

  1. Click image to expand the output configuration.

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

    • Logstores: Select the destination LogStore.

    • Compression Method: lz4 and zstd are supported.

    • Route Settings: Route logs based on tag fields. The system uploads matching logs to the destination LogStore. If this configuration is empty, the system uploads all collected logs to this destination.

      • Tag Name: The name of the tag field used for routing. Enter only the field name (for example, __path__), without the __tag__: prefix. Tag fields fall into two categories:

        Tags are described in Manage LoongCollector collection tags.
        • Agent-related: Related to the collection agent and independent of plugins. Examples include __hostname__ and __user_defined_id__.

        • Input plugin-related: Provided by input plugins to enrich logs with contextual information. Examples include __path__ for file collection and _pod_name_ or _container_name_ for Kubernetes collection.

      • Tag Value: If a log's tag field matches this value, the system sends the log to this destination LogStore.

      • Discard this tag?: If enabled, the system removes this tag field from logs before uploading them.

Step 4: Configure query and analysis

After you configure log processing and plug-ins, click Next to go to the Query and Analysis Configurations page:

  • The system enables the full-text index by default, which lets you perform keyword searches on the original log content.

  • To perform precise queries by field, wait for the Preview Data to load on the page, then click Automatic Index Generation. Simple Log Service generates a field index based on the first entry in the preview data.

After the configuration is complete, click Next to complete the collection configuration.

Step 5: View uploaded logs

After you create a collection configuration and apply it to a machine group, it is deployed automatically and starts collecting incremental logs.

  1. Verify new log entries: LoongCollector collects only incremental logs. Run tail -f /path/to/your/log/file and use your application to generate new log entries.

  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 if new logs appear. The default fields for container text logs are as follows:

    Parameter

    Description

    tag:hostname

    The name of the container's host.

    tag:path

    The path of the log file in the container.

    tag:container_ip

    The IP address of the container.

    tag:image_name

    The name of the image used by the container.

    Note

    If multiple images have the same hash but different names or tags, the collection configuration selects one of the names based on the hash. The selected name is not guaranteed to match the one defined in the YAML file.

    tag:pod_name

    The name of the pod.

    tag:namespace

    The namespace to which the pod belongs.

    tag:pod_uid

    The unique identifier (UID) of the pod.

Key configurations for log integrity

These configuration parameters directly affect log collection integrity and reliability.

LoongCollector resource configuration

Proper resource allocation is critical for collection performance in high-volume scenarios. Key parameters:

# Configure CPU and memory resources based on the log generation rate
resources:
  limits:
    cpu: "2000m"       
    memory: "2Gi"
# Parameters that affect collection performance
env:
  - name: cpu_usage_limit
    value: "2"      
  - name: mem_usage_limit
    value: "2048"  
  - name: max_bytes_per_sec
    value: "209715200"
  - name: process_thread_count
    value: "8"                             
  - name: send_request_concurrency
    value: "20"                            

To configure Logtail based on your data volume, see Logtail network types, startup parameters, and configuration files.

Server-side quota configuration

Server-side quota limits or network issues can block data transmission, creating backpressure that affects log integrity. Use CloudLens for SLS to monitor Project resource quotas.

Initial collection configuration optimization

The initial file collection policy at pod startup affects log integrity, especially in high-throughput scenarios.

The initial collection size specifies where collection begins in a new file. Default: 1024 KB.

  • If a file is smaller than 1024 KB, collection starts from its beginning.

  • If a file is larger than 1024 KB, collection starts 1024 KB from its end.

  • The initial collection size can range from 0 to 10,485,760 KB (10 GB).

enable_full_drain_mode

Ensures LoongCollector completes all data collection and transmission before terminating upon receiving a SIGTERM signal.

# Parameter that affects collection integrity
env:
  - name: enable_full_drain_mode
    value: "true"                          # Enable full drain mode

FAQ

Manage multi-destination distribution configurations

Multi-destination distribution configurations apply to multiple LogStores and must be managed at the Project level:

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

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

    Note

    This page centralizes management of all collection configurations within the Project, including those remaining after a LogStore is deleted.

Next steps

  1. Data visualization: Use a visualization dashboard to monitor trends in key metrics.

  2. Automated alerting for data anomalies: Set up alert policies to detect system anomalies in real time.

  3. SLS collects only incremental logs. To collect historical logs, see Import historical log files.

Appendix: YAML example

A complete Kubernetes configuration with an Nginx application container and a LoongCollector sidecar container.

Before using this configuration, replace the following placeholders:

  1. Replace ${your_aliyun_user_id} with your Alibaba Cloud account ID.

  2. Replace ${your_machine_group_user_defined_id} with the custom identifier of the machine group that you created in Step 3 . The value must match exactly.

  3. Replace ${your_region_config} with the configuration name that matches the region and network type of your SLS project.

    Example: If your project is in the China (Hangzhou) region, use cn-hangzhou for internal network access or cn-hangzhou-internet for public network access.

Short-lived tasks (Job/CronJob)

apiVersion: batch/v1
kind: Job
metadata:
  name: demo-job
spec:
  backoffLimit: 3                   
  activeDeadlineSeconds: 3600        
  completions: 1                     
  parallelism: 1                    
  template:
    spec:
      restartPolicy: Never         
      terminationGracePeriodSeconds: 300 
      containers:
        # Application container
        - name: demo-job
          image: debian:bookworm-slim
          command: ["/bin/bash", "-c"]
          args:
            - |
              # Wait for LoongCollector to be ready.
              echo "[$(date)] Business: Waiting for LoongCollector to be ready..."
              until [[ -f /tasksite/cornerstone ]]; do 
                sleep 1
              done
              echo "[$(date)] Business: LoongCollector is ready, starting business logic"
              # Run the application logic.
              echo "Hello, World!" >> /app/logs/business.log
              # Save the exit code.
              retcode=$?
              echo "[$(date)] Business: Task completed with exit code: $retcode"
              # Notify LoongCollector that the task is finished.
              touch /tasksite/tombstone
              echo "[$(date)] Business: Tombstone created, exiting"
              exit $retcode
          # Resource requests and limits
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "500"
              memory: "512Mi"
          # volume mounts
          volumeMounts:
            - name: app-logs
              mountPath: /app/logs
            - name: tasksite
              mountPath: /tasksite
        # LoongCollector sidecar container
        - name: loongcollector
          image: aliyun-observability-release-registry.cn-hongkong.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
          command: ["/bin/bash", "-c"]
          args:
            - |
              echo "[$(date)] LoongCollector: Starting initialization"
              # Start the LoongCollector service.
              /etc/init.d/loongcollectord start
              # Wait for the configuration to download and the service to be ready.
              sleep 15
              # Verify the service status.
              if /etc/init.d/loongcollectord status; then
                echo "[$(date)] LoongCollector: Service started successfully"
                touch /tasksite/cornerstone
              else
                echo "[$(date)] LoongCollector: Failed to start service"
                exit 1
              fi
              # Wait for the application container to finish.
              echo "[$(date)] LoongCollector: Waiting for business container to complete"
              until [[ -f /tasksite/tombstone ]]; do 
                sleep 2
              done
              echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
              # Allow sufficient time to send remaining logs.
              sleep 30
              echo "[$(date)] LoongCollector: Stopping service"
              /etc/init.d/loongcollectord stop
              echo "[$(date)] LoongCollector: Shutdown complete"
          # health check
          livenessProbe:
            exec:
              command: ["/etc/init.d/loongcollectord", "status"]
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 3
          # Resource requests and limits
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "500m"
              memory: "512Mi"
          # environment variables
          env:
            - name: ALIYUN_LOGTAIL_USER_ID
              value: "your-user-id"
            - name: ALIYUN_LOGTAIL_USER_DEFINED_ID
              value: "your-user-defined-id"
            - name: ALIYUN_LOGTAIL_CONFIG
              value: "/etc/ilogtail/conf/cn-hongkong/ilogtail_config.json"
            - name: ALIYUN_LOG_ENV_TAGS
              value: "_pod_name_|_pod_ip_|_namespace_|_node_name_"
            # Inject pod metadata.
            - name: "_pod_name_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: "_pod_ip_"
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: "_namespace_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: "_node_name_"
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
          # volume mounts
          volumeMounts:
            - name: app-logs
              mountPath: /app/logs
              readOnly: true
            - name: tasksite
              mountPath: /tasksite
            - name: tz-config
              mountPath: /etc/localtime
              readOnly: true
      # Volume definitions
      volumes:
        - name: app-logs
          emptyDir: {}
        - name: tasksite
          emptyDir:
            medium: Memory
            sizeLimit: "10Mi"
        - name: tz-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Shanghai

Long-lived services (Deployment / StatefulSet)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-demo
  namespace: production
  labels:
    app: nginx-demo
    version: v1.0.0
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1      
      maxSurge: 1          
  selector:
    matchLabels:
      app: nginx-demo
  template:
    metadata:
      labels:
        app: nginx-demo
        version: v1.0.0    
    spec:
      terminationGracePeriodSeconds: 600  # 10-minute graceful shutdown period
      containers:
        # Application container - Web application
        - name: nginx-demo
          image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6          
          # Startup command and signal handling
          command: ["/bin/sh", "-c"]
          args:
            - |
              # Define the signal handler.
              _term_handler() {
                  echo "[$(date)] [nginx-demo] Caught SIGTERM, starting graceful shutdown..."
                  # Send the QUIT signal to Nginx for a graceful stop.
                  if [ -n "$NGINX_PID" ]; then
                      kill -QUIT "$NGINX_PID" 2>/dev/null || true
                      echo "[$(date)] [nginx-demo] Sent SIGQUIT to Nginx PID: $NGINX_PID"
                      # Wait for Nginx to stop gracefully.
                      wait "$NGINX_PID"
                      EXIT_CODE=$?
                      echo "[$(date)] [nginx-demo] Nginx stopped with exit code: $EXIT_CODE"
                  fi
                  # Notify LoongCollector that the application container has stopped.
                  echo "[$(date)] [nginx-demo] Writing tombstone file"
                  touch /tasksite/tombstone
                  exit $EXIT_CODE
              }
              # Register the signal handler.
              trap _term_handler SIGTERM SIGINT SIGQUIT
              # Wait for LoongCollector to be ready.
              echo "[$(date)] [nginx-demo]: Waiting for LoongCollector to be ready..."
              until [[ -f /tasksite/cornerstone ]]; do 
                sleep 1
              done
              echo "[$(date)] [nginx-demo]: LoongCollector is ready, starting business logic"
              # Start Nginx.
              echo "[$(date)] [nginx-demo] Starting Nginx..."
              nginx -g 'daemon off;' &
              NGINX_PID=$!
              echo "[$(date)] [nginx-demo] Nginx started with PID: $NGINX_PID"
              # Wait for the Nginx process to exit.
              wait $NGINX_PID
              EXIT_CODE=$?
              # If the process exits without a signal, notify LoongCollector.
              if [ ! -f /tasksite/tombstone ]; then
                  echo "[$(date)] [nginx-demo] Unexpected exit, writing tombstone"
                  touch /tasksite/tombstone
              fi
              exit $EXIT_CODE
          # Resource requests and limits
          resources:
            requests:
              cpu: "200m"
              memory: "256Mi"
            limits:
              cpu: "1000m"
              memory: "1Gi"
          # volume mounts
          volumeMounts:
            - name: nginx-logs
              mountPath: /var/log/nginx
            - name: tasksite
              mountPath: /tasksite
            - name: tz-config
              mountPath: /etc/localtime
              readOnly: true
        # LoongCollector sidecar container
        - name: loongcollector
          image: aliyun-observability-release-registry.cn-shenzhen.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
          command: ["/bin/bash", "-c"]
          args:
            - |
              echo "[$(date)] LoongCollector: Starting initialization"
              # Start the LoongCollector service.
              /etc/init.d/loongcollectord start
              # Wait for the configuration to download and the service to be ready.
              sleep 15
              # Verify the service status.
              if /etc/init.d/loongcollectord status; then
                echo "[$(date)] LoongCollector: Service started successfully"
                touch /tasksite/cornerstone
              else
                echo "[$(date)] LoongCollector: Failed to start service"
                exit 1
              fi
              # Wait for the application container to finish.
              echo "[$(date)] LoongCollector: Waiting for business container to complete"
              until [[ -f /tasksite/tombstone ]]; do 
                sleep 2
              done
              echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
              # Allow sufficient time to send remaining logs.
              sleep 30
              echo "[$(date)] LoongCollector: Stopping service"
              /etc/init.d/loongcollectord stop
              echo "[$(date)] LoongCollector: Shutdown complete"
          # health check
          livenessProbe:
            exec:
              command: ["/etc/init.d/loongcollectord", "status"]
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 3
          # Resource requests and limits
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "2000m"
              memory: "2048Mi"
          # environment variables
          env:
            - name: ALIYUN_LOGTAIL_USER_ID
              value: "${your_aliyun_user_id}"
            - name: ALIYUN_LOGTAIL_USER_DEFINED_ID
              value: "${your_machine_group_user_defined_id}"
            - name: ALIYUN_LOGTAIL_CONFIG
              value: "/etc/ilogtail/conf/${your_region_config}/ilogtail_config.json"
            # Enable full drain mode to send all logs when the pod stops.
            - name: enable_full_drain_mode
              value: "true"
            # Append pod environment information as log tags.
            - name: "ALIYUN_LOG_ENV_TAGS"
              value: "_pod_name_|_pod_ip_|_namespace_|_node_name_|_node_ip_"
            # Get pod and node information.
            - name: "_pod_name_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: "_pod_ip_"
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: "_namespace_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: "_node_name_"
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: "_node_ip_"
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
          # volume mounts
          volumeMounts:
            - name: nginx-logs
              mountPath: /var/log/nginx
              readOnly: true
            - name: tasksite
              mountPath: /tasksite
            - name: tz-config
              mountPath: /etc/localtime
              readOnly: true
      # Volume definitions
      volumes:
        - name: nginx-logs
          emptyDir: {}
        - name: tasksite
          emptyDir:
            medium: Memory
            sizeLimit: "50Mi"
        - name: tz-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Shanghai

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.

Regex parsing

Use regular expressions to extract fields from logs into key-value pairs for independent querying and analysis.

Example:

Raw log without any processing

Using the regular expression parsing plug-in

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: In the Processor Configurations section of the Logtail Configurations page, click Add Processor and select Native Processor > Data Parsing (Regex Mode).

  • Regular Expression: A regular expression to match log content. You can generate it automatically or enter it manually.

    • Auto-generate:

      • Click Generate.

      • In the Log Sample box, select the log content to extract.

      • Click Generate Regular Expression.

        For example, if you paste a log in Apache Combined format into the Log Sample box, it will contain fields such as client IP, timestamp, request method and path, status code, Referer, and User-Agent.

    • Manual entry: Manually Enter Regular Expression based on the log format.

    After entering the expression, click Validate to test if it correctly parses the log content.

  • Extracted Field: Set a field name (key) for each piece of extracted log content (value).

  • For information about other parameters, see the general parameter descriptions in Use case 2: Structured logs.


Delimiter parsing

Use delimiter parsing to split log content into key-value pairs. Supports single-character and multi-character delimiters.

Example:

Raw log without any processing

Split fields by the specified 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: In the Processor Configurations section of the Logtail Configurations page, click Add Processor and select Native Processor > Data Parsing (Delimiter Mode).

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

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

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

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

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

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

    • Can be up to 128 bytes in length.

  • For information about other parameters, see the general parameter descriptions in Use case 2: Structured logs.


JSON parsing

Parses logs formatted as JSON objects into key-value pairs.

Example:

Raw log without any processing

Automatic extraction of standard JSON key-values

{"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: In the Processor Configurations section of the Logtail Configurations page, click Add Processor and select Native Processor > Data Parsing (JSON Mode).

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

  • For information about other parameters, see the general parameter descriptions in Use case 2: Structured logs.


Expanding JSON fields

Expands a field containing a nested JSON object into multiple key-value pairs.

Example:

Raw log without any processing

Expansion depth: 0, using expansion depth as a prefix

Expansion depth: 1, using expansion depth as a prefix

{"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: In the Processor Configurations section of the Logtail Configurations page, 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: The expansion level of the JSON object. A value of 0 (the default) fully expands the object, 1 expands only the current level, and so on.

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

  • Name Prefix of Expanded Keys: A prefix to add to the field names after JSON expansion.

  • Expand Array: Turn on this switch to expand arrays 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), add a Rename Fields processor to complete the mapping.
  • For information about other parameters, see the general parameter descriptions in Use case 2: Structured logs.


JSON array parsing

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

Example:

Raw log without any processing

Extract JSON array structure

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

Procedure: On the Logtail Configuration page, in the Processor Configurations area, 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 log field content and store the results in new fields json1 and json2.

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

Apache log parsing

Structure log content based on the definitions in your Apache log configuration file, parsing it into multiple key-value pairs.

Example:

Raw log without any processing

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: In the Processor Configurations section of the Logtail Configurations page, 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

    Ensure the auto-populated content exactly matches the LogFormat definition in your server's Apache configuration file (typically /etc/apache2/apache2.conf).

  • For information about other parameters, see the general parameter descriptions in Use case 2: Structured logs.


Data Masking

Mask sensitive data in logs.

Example:

Raw log without any processing

Masking 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 area, click Add Processor and select Native Processor > Data Masking:

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

  • Data Masking Method:

    • const: Replaces sensitive content with the specified string.

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

  • Replacement String: When you select const for Data Masking Method, you need to enter a string to replace the sensitive content.

  • Content Expression that Precedes Replaced Content: Used to find sensitive content. Configure using RE2 syntax.

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


Time Parsing

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

Example:

Raw log without any processing

Time parsing

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

In the SLS log details view, the JSON log is correctly parsed into structured fields. Each field (cluster, level, message, time, userId) and its value are displayed independently.

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

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

  • Time Format: Set the corresponding time format based on the time content in the log.

  • Time Zone: Select the time zone of the log time field. By default, the machine time zone is used, which is the time zone of the environment where the LoongCollector (Logtail) process is running.

Regular expression limitations for container filtering

Regular expressions for container filtering use the Go RE2 engine, which has syntax limitations compared to PCRE.

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 syntax: (?P<year>\d{4})

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

2. Unsupported regular expression features

The RE2 engine does not support the following common but complex regular expression features:

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

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

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

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

  • Atomic groups: (?>...)

3. Recommendations

Use tools such as Regex101 to debug regular expressions. Select the Golang (RE2) mode to ensure compatibility. Unsupported syntax prevents correct parsing or matching.