Ravindra BagaleCourses & study guides मराठी

Chapter 14: Logging and Light Observability

DevOps

14.5 Log groups, streams and agents (conceptual)

Why: the problem

Suppose TCS runs a client's Java app on 10 EC2 servers. The app writes to /var/log/app/app.log. Docker is not used, so the awslogs driver does not help. How do these files reach CloudWatch? We install a small program on every server called an agent. The agent reads the log files, like tail -f, and ships new lines to CloudWatch. On AWS the official one is the CloudWatch agent. Other teams use Fluent Bit or Promtail. The agent also decides the group and stream names. Good names make search easy. Bad names make a mess. In this lesson we set up the agent on Amazon Linux, ship nginx and Java logs, and see Fluent Bit doing the same job.

What we will build

You will install the CloudWatch agent, write its JSON config to ship two files with clear group and stream names, start it and check it, then ship Docker logs with Fluent Bit, and set a retention policy on the groups.

What: every term in plain English

  • Agent — A small program on each server that reads logs and ships them.
  • CloudWatch agent — The official AWS agent. It ships logs and server metrics.
  • Fluent Bit — A light open source log shipper used a lot with Docker and Kubernetes.
  • file_path — The log file the agent should read.
  • {instance_id} — A placeholder the agent replaces with the server id, like i-0abc123.
  • Retention — How many days CloudWatch keeps logs before deleting them.
  • Naming convention — A fixed pattern for names, like /company/app/env.
  • CloudWatchAgentServerPolicy — The AWS managed policy the server role needs for the agent.
Attach the role Install the agent Write the config Load and start Check status See the lines in CloudWatch
Agent: file on server to agent to group per app, stream per server

How: step by step

  1. Attach the role

    In the EC2 console: Actions > Security > Modify IAM role > pick a role with CloudWatchAgentServerPolicy
    

    What it does: Gives the server permission to ship logs.

    Output

    Successfully attached
    
  2. Install the agent

    sudo dnf install -y amazon-cloudwatch-agent
    

    What it does: Amazon Linux 2023 has it in its repo.

    Output

    Installed: amazon-cloudwatch-agent-1.300...
    
  3. Write the config

    sudo nano /opt/aws/amazon-cloudwatch-agent/etc/config.json  (paste Example 1)
    

    What it does: Tells the agent which files go where.

    Output

    (file saved)
    
  4. Load and start

    sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/etc/config.json -s
    

    What it does: Reads the config and starts the agent.

    Output

    amazon-cloudwatch-agent has been started
    
  5. Check status

    sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status
    

    What it does: Should show running.

    Output

    {
      "status": "running",
      "configstatus": "configured"
    }
    
  6. See the lines in CloudWatch

    aws logs tail /tcs/orders/prod/nginx-access --since 5m --format short
    

    What it does: New nginx lines appear.

    Output

    05:01:10 i-0abc123 10.0.1.5 - - "GET /health HTTP/1.1" 200
    

Example 1: CloudWatch agent config for nginx and a Java app

Stack. Amazon Linux 2023, CloudWatch agent, nginx, Java

Goal. CloudWatch agent config for nginx and a Java app.

config.json

{
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          {
            "file_path": "/var/log/nginx/access.log",
            "log_group_name": "/tcs/orders/prod/nginx-access",
            "log_stream_name": "{instance_id}",
            "retention_in_days": 30
          },
          {
            "file_path": "/var/log/app/app.log",
            "log_group_name": "/tcs/orders/prod/app",
            "log_stream_name": "{instance_id}",
            "timestamp_format": "%Y-%m-%d %H:%M:%S",
            "multi_line_start_pattern": "{timestamp_format}",
            "retention_in_days": 30
          }
        ]
      }
    }
  }
}

What each line does

  • collect_list — A list of files to ship.
  • log_group_name — Pattern /company/app/env/source. Easy to search and to set retention.
  • log_stream_name: {instance_id} — One stream per server.
  • multi_line_start_pattern — A Java stack trace has many lines. This keeps them in one event.
  • retention_in_days: 30 — The agent sets 30 day retention on the group.

Green output

$ aws logs describe-log-groups --log-group-name-prefix /tcs/orders/prod --query "logGroups[].[logGroupName,retentionInDays]" --output text
/tcs/orders/prod/app            30
/tcs/orders/prod/nginx-access   30

Expected result. Both groups exist with 30 day retention, and each server has its own stream.

Example 2: Fluent Bit ships Docker container logs to CloudWatch

Stack. Docker, Fluent Bit, CloudWatch

Goal. Fluent Bit ships Docker container logs to CloudWatch.

fluent-bit.conf

[INPUT]
    Name   tail
    Path   /var/lib/docker/containers/*/*.log
    Parser docker
    Tag    docker.*

[OUTPUT]
    Name              cloudwatch_logs
    Match             docker.*
    region            ap-south-1
    log_group_name    /tcs/orders/prod/containers
    log_stream_prefix fb-
    auto_create_group true

Run Fluent Bit

docker run -d --name fluentbit \
  -v /var/lib/docker/containers:/var/lib/docker/containers:ro \
  -v "$PWD/fluent-bit.conf":/fluent-bit/etc/fluent-bit.conf:ro \
  public.ecr.aws/aws-observability/aws-for-fluent-bit:stable

What each line does

  • [INPUT] Name tail — Read files like tail -f.
  • Path ...-json.log files — The json-file logs Docker writes for every container.
  • Parser docker — Understands the Docker JSON line format.
  • [OUTPUT] cloudwatch_logs — Ship to CloudWatch Logs.
  • :ro — Mount read only. Fluent Bit cannot change your logs.

Green output

$ docker logs fluentbit | tail -n 2
[2026/10/25 05:10:02] [ info] [output:cloudwatch_logs:cloudwatch_logs.0] Created log stream fb-docker.var.lib.docker.containers.8d2c...
[2026/10/25 05:10:03] [ info] [output:cloudwatch_logs:cloudwatch_logs.0] Sent 42 events to CloudWatch

Expected result. Containers keep the json-file driver for docker logs, and Fluent Bit copies the lines to CloudWatch.

Example 3: Set retention and check naming with a script

Stack. AWS CLI v2, bash

Goal. Set retention and check naming with a script.

retention.sh

#!/usr/bin/env bash
set -euo pipefail
for g in $(aws logs describe-log-groups --log-group-name-prefix /tcs/ \
             --query "logGroups[].logGroupName" --output text); do
  aws logs put-retention-policy --log-group-name "$g" --retention-in-days 30
  echo "30 days: $g"
done
aws logs describe-log-groups --query "logGroups[?retentionInDays==null].logGroupName" --output text

What each line does

  • describe-log-groups ... --output text — Lists group names as plain words for the loop.
  • put-retention-policy — Sets how many days to keep logs.
  • retentionInDays==null — Finds groups that keep logs forever. These cost money every month.

Green output

$ bash retention.sh
30 days: /tcs/orders/prod/app
30 days: /tcs/orders/prod/containers
30 days: /tcs/orders/prod/nginx-access
/aws/lambda/old-test-fn

Expected result. You fixed your groups and found one old Lambda group that keeps logs forever.

Verify: did it work?

  1. Agent log file

    sudo tail -n 5 /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log
    

    What it does: The agent writes its own log. Errors appear here.

    Output

    2026-10-25T05:01:00Z I! [logagent] piping log from /tcs/orders/prod/app/i-0abc123(/var/log/app/app.log)
    
  2. Count streams

    aws logs describe-log-streams --log-group-name /tcs/orders/prod/app --query "length(logStreams)"
    

    What it does: One per server.

    Output

    10
    

When it is red 1

E! cloudwatchlogs: AccessDeniedException ... is not authorized to perform: logs:PutLogEvents

Cause. The EC2 role is missing CloudWatchAgentServerPolicy.

Fix, step by step

  1. Attach the policy to the instance role.
  2. Wait one minute.
  3. Restart: amazon-cloudwatch-agent-ctl -a stop then -a start.

When it is red 2

Stack traces split into many events

Cause. No multi_line_start_pattern for the Java log.

Fix, step by step

  1. Add multi_line_start_pattern with your timestamp format.
  2. Reload the config with fetch-config.
  3. Throw a test error and check one event holds the trace.

When it is red 3

Nothing ships, agent log says: open /var/log/app/app.log: permission denied

Cause. The agent user cannot read the file.

Fix, step by step

  1. Make the agent run as root (default), or add it to the group that owns the file.
  2. Do not open the file to everyone.
  3. Restart the agent.

Cleanup

  1. Stop the agent and Fluent Bit

    sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a stop ; docker rm -f fluentbit
    

    What it does: Stops shipping.

    Output

    fluentbit
    

Ravindra Bagale's Tip

Name the group carefully: /company/app/env. Later, search becomes much easier.

Practice tasks

Easy Name groups well

Why: Clean names save time.

What to do: Write group names for app pay in dev, test, prod.

How:
  1. /company/pay/dev/app and so on.

Check: All follow one pattern.

Medium Add metrics to the agent

Why: The same agent sends memory and disk use.

What to do: Add a metrics section with mem_used_percent.

How:
  1. Use the agent wizard: amazon-cloudwatch-agent-config-wizard

Check: CWAgent metrics appear in CloudWatch.

Hard Fluent Bit with Kubernetes

Why: EKS uses Fluent Bit as a DaemonSet.

What to do: Read the aws-for-fluent-bit DaemonSet YAML and note input and output.

How:
  1. Find Path /var/log/containers/*.log

Check: You can explain where each pod log goes.

Easy Say log agents in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about log agents for a fresher who knows only Linux, Git and Docker basics.

How:
  1. Write the problem it solves.
  2. Write the one command or config line you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Keep a throwaway log lab

Why: Practice needs a lab you can break. If it gets messy, you delete the containers and start again.

What to do: Run a small app in Docker that prints logs every second.

How:
  1. docker run -d --name ticker busybox sh -c "while true; do date; sleep 1; done"
  2. docker logs -f ticker
  3. Press Ctrl+C, then docker rm -f ticker.

Check: You see one new time line every second.

Medium Do it on a second stack

Why: Logging ideas must work for Python, Node.js and Java. Only the library changes.

What to do: Repeat this lesson with a different language than the one you used first.

How:
  1. If you used Python, use Node.js or Spring Boot now.
  2. Keep the same field names: time, level, msg, request_id.
  3. Compare the two outputs side by side.

Check: Both apps print the same fields in the same shape.

Medium Break it on purpose

Why: You must know the red error by face. In a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers log commands. A short page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when to use, exact commands, how to check, how to undo.

Check: A teammate can follow it alone.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the command you ran, the log line you found and the fix.

Check: Your answer has a real command and a real log line.

Hard Draw the flow top to bottom

Why: A drawing shows where a log line is born and where it ends up.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the user click, go through the app, the log driver or agent, and end at the place you search.

Check: Each box matches a real command or file in this lesson.

Homework: try at home

Try at home

At home, ship /var/log/secure (or auth.log) with the agent into /lab/linux/auth and find a failed SSH login in CloudWatch.

Recap

  • Agents ship files that are not Docker stdout.
  • The CloudWatch agent uses a JSON collect_list.
  • Name groups /company/app/env/source and streams by server.
  • Fluent Bit is the light shipper for containers.
  • Always set retention.

FAQ

Agent or awslogs driver?

Containers: driver or Fluent Bit. Plain files on EC2: agent.

Does the agent slow the server?

Very little. It uses some CPU and memory; watch it on tiny instances.

Can one agent ship to two groups?

Yes, one collect_list entry per file.

What if the agent is down for an hour?

It remembers its position and sends the missed lines later, if the file was not deleted.

Is Fluentd the same as Fluent Bit?

Same family. Fluent Bit is lighter and is the default for containers.

Interview questions

  1. How do you ship app log files from EC2 to CloudWatch?

    Install the CloudWatch agent, give the instance role CloudWatchAgentServerPolicy, list files in collect_list, start it with fetch-config.

  2. How do you handle multi-line logs like stack traces?

    Set multi_line_start_pattern so lines that do not start with a timestamp join the previous event.

  3. How do you name log groups?

    By company, app, environment and source, for example /tcs/orders/prod/app.

  4. What is Fluent Bit used for?

    Light log collection and forwarding, often as a DaemonSet on Kubernetes.

  5. Why set retention?

    Logs without retention are kept forever and cost grows every month.

Quick quiz

Q1. What does an agent do?

Reads log files on a server and ships new lines to a central store.

Q2. Which policy does the CloudWatch agent need?

CloudWatchAgentServerPolicy.

Q3. What does {instance_id} do?

Names the stream after the server id.

Q4. Why multi_line_start_pattern?

To keep one stack trace in one event.

Q5. Name another shipper.

Fluent Bit, Fluentd, Promtail, Vector.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards