Collect and analyze ECS text logs using LoongCollector

更新时间:
复制 MD 格式

This quick start shows you how to use LoongCollector, a data collector for Simple Log Service (SLS), to collect Nginx logs from an ECS instance. In about 30 minutes, you will learn how to configure log collection, analyze data with SQL, view a dashboard, set up alerts, and clean up all created resources to avoid fees.

image

Prerequisites

Activate service and prepare an account

  • Activate Simple Log Service: If this is your first time, log on to the Simple Log Service console and follow the on-screen instructions to activate the service.

  • Prepare an account:

    • Alibaba Cloud account: This account has full permissions by default.

    • RAM user: If you use a RAM user, you must grant it the required permission policies:

      • AliyunLogFullAccess: Grants permissions to create and manage Simple Log Service resources such as projects and logstores.

      • AliyunECSFullAccess: Grants permissions to install the collection agent on an ECS instance.

      • AliyunOOSFullAccess: Grants permissions to automatically install the collection agent on an ECS instance through Operation Orchestration Service (OOS).

      In a production environment, you can create custom permission policies for more granular control over RAM user permissions.

Prepare an ECS instance

Ensure that the security group rules for the ECS instance allow outbound traffic on port 80 (HTTP) and port 443 (HTTPS).

Generate mock logs

  1. Log on to the ECS instance.

  2. Create a script file named generate_nginx_logs.sh and paste the following content. This script writes a standard Nginx access log entry to /var/log/nginx/access.log every 5 seconds.

    generate_nginx_logs.sh

    #!/bin/bash
    
    #==============================================================================
    # Script Name: generate_nginx_logs.sh
    # Script Description: Simulates an NGINX server and continuously writes logs to access.log.
    #==============================================================================
    
    # --- Configurable Parameters ---
    
    # Log file path
    LOG_FILE="/var/log/nginx/access.log"
    
    # --- Mock Data Pools ---
    
    # Random IP address pool
    IP_ADDRESSES=(
        "192.168.1.10" "10.0.0.5" "172.16.31.40" "203.0.113.15"
        "8.8.8.8" "1.1.X.X" "91.198.XXX.XXX" "114.114.114.114"
        "180.76.XX.XX" "223.5.5.5"
    )
    
    # HTTP request method pool
    HTTP_METHODS=("GET" "POST" "PUT" "DELETE" "HEAD")
    
    # Common request path pool
    REQUEST_PATHS=(
        "/index.html" "/api/v1/users" "/api/v1/products?id=123" "/images/logo.png"
        "/static/js/main.js" "/static/css/style.css" "/login" "/admin/dashboard"
        "/robots.txt" "/sitemap.xml" "/non_existent_page.html"
    )
    
    # HTTP status code pool (You can adjust the weights, for example, add more 200s to increase their probability)
    HTTP_STATUSES=(200 200 200 200 201 301 404 404 500 502 403)
    
    # Common User-Agent pool
    USER_AGENTS=(
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"
        "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/604.1"
        "Mozilla/5.0 (Linux; Android 11; SM-G991U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36"
        "curl/7.68.0"
        "Googlebot/2.1 (+http://www.google.com/bot.html)"
    )
    
    # Common Referer pool
    REFERERS=(
        "https://www.google.com/"
        "https://www.bing.com/"
        "https://github.com/"
        "https://stackoverflow.com/"
        "-"
        "-"
        "-"
    )
    # Check and create the log directory
    LOG_DIR=$(dirname "$LOG_FILE")
    if [ ! -d "$LOG_DIR" ]; then
        echo "Log directory '$LOG_DIR' does not exist. Attempting to create..."
        # Use sudo to create the directory because root permissions are usually required
        sudo mkdir -p "$LOG_DIR"
        if [ $? -ne 0 ]; then
            echo "Error: Failed to create directory '$LOG_DIR'. Check permissions or create it manually."
            exit 1
        fi
        echo "Directory created successfully."
    fi
    
    # Check write permissions for the log file
    trap 'echo -e "\n\nScript interrupted. Stopping log generation..."; exit 0;' SIGINT
    
    # --- Core Function ---
    
    # Define a function to randomly select an element from an array
    # Usage: random_element "array_name"
    function random_element() {
        local arr=("${!1}")
        echo "${arr[$((RANDOM % ${#arr[@]}))]}"
    }
    
    # Catch the Ctrl+C interrupt signal for a graceful exit
    trap 'echo -e "\n\nScript interrupted. Stopping log generation..."; exit 0;' SIGINT
    
    # --- Main Loop ---
    
    echo "Start generating mock NGINX logs to $LOG_FILE ..."
    echo "A log entry is generated every 5 seconds."
    echo "Press Ctrl+C to stop."
    sleep 2
    
    # Infinite loop to continuously generate logs
    while true; do
        # 1. Get the current time in the default NGINX format: [dd/Mon/YYYY:HH:MM:SS +ZZZZ]
        timestamp=$(date +'%d/%b/%Y:%H:%M:%S %z')
    
        # 2. Randomly select data from the pools
        ip=$(random_element IP_ADDRESSES[@])
        method=$(random_element HTTP_METHODS[@])
        path=$(random_element REQUEST_PATHS[@])
        status=$(random_element HTTP_STATUSES[@])
        user_agent=$(random_element USER_AGENTS[@])
        referer=$(random_element REFERERS[@])
    
        # 3. Generate a random response body size (in bytes)
        bytes_sent=$((RANDOM % 5000 + 100)) # A random number between 100 and 5100
    
        # 4. Concatenate into a complete NGINX combined format log entry
        # Format: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
        log_line="$ip - - [$timestamp] \"$method $path HTTP/1.1\" $status $bytes_sent \"$referer\" \"$user_agent\""
    
        # 5. Append the log line to the file
        # echo "$log_line" >> "$LOG_FILE"
        echo "$log_line" | sudo tee -a "$LOG_FILE" > /dev/null
        
        # 6. Wait for 5 seconds before the next loop
        sleep 5
    done
  3. Grant execution permissions: chmod +x generate_nginx_logs.sh.

  4. Run the script in the background: nohup ./generate_nginx_logs.sh &.

Create a project and logstore

A project is the basic resource management unit in Simple Log Service. It isolates and manages data. A logstore is the storage unit for log data within a project.

  1. Log on to the Simple Log Service console.

  2. Click Create Project:

    • Region: Select the same region as your ECS instance. This allows you to collect logs over the Alibaba Cloud internal network for faster log collection.

    • Project Name: Enter a globally unique name within Alibaba Cloud, such as nginx-quickstart-abc.

  3. Keep the default settings for other configurations and click Create.

  4. After the project is created, click Create Logstore.

  5. Enter a Logstore Name (for example, nginx-access-log), keep the default settings for the other configurations, and click OK.

    By default, a Standard logstore is created, which is billed based on the volume of data written.

Install LoongCollector

  1. After the logstore is created, click OK in the confirmation dialog box to open the Quick Data Import panel.

  2. On the Nginx - Text Logs card, click Integrate Now.

  3. Machine Group Configurations:

    • Scenario: Servers

    • Installation Environment: ECS

  4. Click Create Machine Group. In the panel that appears, select the target ECS instance.

  5. Click Install and Create Machine Group. After the installation is successful, enter a Name for the machine group, such as my-nginx-server, and then click OK.

    Note

    If the installation fails or remains pending, ensure the ECS region is the same as the project region.

  6. Click Next to proceed to the heartbeat status check.

    When you create a machine group for the first time, if the heartbeat status is FAIL, click Automatic Retry. The status changes to OK in about two minutes.

Create a collection configuration

  1. After the heartbeat status is OK, click Next to go to the Logtail Configurations page:

    • Configuration Name: Enter a name for the configuration, such as nginx-access-log-config.

    • File Path: Enter /var/log/nginx in the first box and access.log in the second box.

    • Processor Configurations:

      • Log Sample: Click Add Sample Log and paste a sample log entry:

        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"
      • Processing Method: Click Data Parsing (NGINX Mode). In the NGINX Log Configuration section, configure log_format by copying and pasting the following content. Then, click Confirm.

        log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" $request_time $request_length';
        In a production environment, the log_format specified here must match the definition in your Nginx configuration file (usually in /etc/nginx/nginx.conf).

        Log parsing 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: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/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
  2. Click Next to go to the Query and Analysis Configurations page. It takes about 1 minute for the collection configuration to take effect. Click Automatic Refresh. Preview data indicates that the configuration is effective.

Query and analyze logs

Click End to go to the End page, and then click Query Log. You are redirected to the query and analysis page of the target logstore. Write SQL statements to extract key business and O&M metrics from structured logs. Set the time range to Last 15 Minutes:

Note

If an error pop-up appears, it is because the index is not yet configured. Close the pop-up and wait for 1 minute. You can then view the log content from the access.log file.

  • Example 1: Total page views (PV)

    Count the total number of log entries in the specified time range.

    * | SELECT count(*) AS pv
  • Example 2: Requests and error rate per minute

    Calculate the total number of requests, the number of error requests (HTTP status code ≥ 400), and the error rate per minute.

    * | SELECT 
      date_trunc('minute', __time__) as time,
      count(1) as total_requests,
      count_if(status >= 400) as error_requests,
      round(count_if(status >= 400) * 100.0 / count(1), 2) as error_rate
    GROUP BY time 
    ORDER BY time DESC 
    LIMIT 100
    
  • Example 3: PVs by request method (GET, POST, etc.)

    Group and count page views by minute and request method, such as GET or POST.

    * |
    SELECT
        date_format(minute, '%m-%d %H:%i') AS time,
        request_method,
        pv
    FROM (
        SELECT
            date_trunc('minute', __time__) AS minute,
            request_method,
            count(*) AS pv
        FROM
            log
        GROUP BY
            minute,
            request_method
    )
    ORDER BY
        minute ASC
    LIMIT 10000

Visualize data on a dashboard

After you configure the Nginx parsing processor, Simple Log Service automatically creates a preset dashboard named nginx-access-log_Nginx Access Log.

  1. In the left-side navigation pane, choose imageDashboard > Dashboards.

  2. Find and click the dashboard name to view charts for key metrics, such as page views (PVs), unique visitors (UVs), error rate, and request method distribution.

  3. You can customize all charts based on your business needs.

image

Configure monitoring and alerts

Create an alert rule to automatically send notifications when the service behaves abnormally (for example, when errors spike).

  1. In the left-side navigation pane, click imageAlerts.

  2. Create an action policy:

    • On the Notification Policy > Action Policy tab, click Create.

    • Configure the ID and Name (for example, send-notification-to-admin).

    • In Primary Action Policy, click imageAction Group.

    • Select a Notification Method (for example, SMS), configure the Recipient, and select an Alert Template.

    • Click Confirm.

  3. Create an alert rule:

    1. Switch to the Alert Monitoring Rule tab and click Create Alert.

    2. Rule name: Enter a descriptive name, such as Too many server 5xx errors.

    3. Query Statistics: Click Add and configure the query conditions.

      • Logstore: Select nginx-access-log.

      • Query Time Range: 15 minutes (Relative).

      • Search: Enter status >= 500 | SELECT * .

      • Click Preview to confirm that you can query data, and then click OK.

    4. Trigger Condition: Set the condition to trigger a Critical alert when Specific number of entries is >100.

      This configuration triggers an alert if more than 100 5xx errors occur within 15 minutes.
    5. Destination: Select SLS Notification and Enable it.

      • Action Policy: Select the action policy you created in the previous step.

      • Repeat Interval: Set this to 15 minutes to prevent excessive repeated notifications.

    6. Click OK to save the alert rule.

  4. Verification: When the trigger condition is met, the configured notification channel receives an alert. You can view all triggered alerts on the Alert History page.

Resource cleanup

To avoid unnecessary fees, clean up all resources created during this tutorial.

  1. Stop the log generation script

    Log on to the ECS instance and run the following command to stop the log generation script running in the background.

    kill $(ps aux | grep '[g]enerate_nginx_logs.sh' | awk '{print $2}')
  2. Uninstall LoongCollector (optional)

    1. For example, you can replace ${region_id} with cn-hangzhou. For the best performance, replace ${region_id} with the region ID of your ECS instance.

      wget https://aliyun-observability-release-${region_id}.oss-${region_id}.aliyuncs.com/loongcollector/linux64/latest/loongcollector.sh -O loongcollector.sh;
    2. Run the uninstall command.

      chmod +x loongcollector.sh; sudo ./loongcollector.sh uninstall;
  3. Delete the project

    1. On the project list page of the Simple Log Service console, find the project that you created, such as nginx-quickstart-xxx.

    2. In the Actions column, click Delete.

    3. In the panel that appears, enter the project name and select a reason for deletion.

    4. Click OK. Deleting a project also deletes all its associated resources, including logstores, collection configurations, dashboards, and alert rules.

    Warning

    After a project is deleted, all its log data and configurations are permanently removed and cannot be recovered. To prevent accidental data loss, confirm this action before you proceed.

Next steps

You have completed the full workflow: log collection, query and analysis, dashboard visualization, and alert configuration. Read the following documents to understand the key concepts and plan your log resources based on your business needs:

FAQ

Inconsistent log time after collection

By default, the time field (__time__) in Simple Log Service uses the time the log arrives at the server. To use the time in the original log text, add a time parsing plug-in to the collection configuration.

Charges for creating a project and logstore

When you create a logstore, Simple Log Service reserves shard resources by default. This may incur active shard lease fees. For more information, see Why am I charged for active shard lease fees?

Troubleshooting log collection failures

Log collection with Logtail may fail due to abnormal Logtail heartbeats, collection errors, or incorrect Logtail collection configurations. For troubleshooting steps, see Troubleshooting Logtail log collection failures.

Failure to analyze logs

To analyze logs, you must configure field indexes for the relevant fields and enable the statistical analysis feature. Check the index configuration of your logstore.

Stopping billing

Simple Log Service cannot be disabled after it is activated. If you no longer want to use the service, you can stop billing by deleting all projects under your account.