DevOps Log Analyzer with Python
Build a Python CLI that turns application logs into resilient JSON summaries.
Introduction
30 Second Summary
When an application starts misbehaving, its log can hide the clue among routine status messages. A broken record can also stop a quick manual check at the worst moment.
In this project, you will build a Python command-line tool that converts an imperfect application log into severity counts. The same run saves a structured JSON report for another automation step.
What You'll Build
A single run against sample.log gives you a readable severity summary plus a structured report.json ready for another tool.
By the end of this project, you'll have:
- A reusable command-line analyzer you can point at a chosen log file from the terminal.
- A concise severity summary showing counts for INFO, WARNING, ERROR, plus malformed records.
- A machine-readable JSON report that preserves the valid counts after malformed input is handled safely.
- Secret Mission: Add an error threshold that makes a CI/CD job fail when the log is unhealthy.
Are there any prerequisites?
You need Windows with Ubuntu running through Windows Subsystem for Linux (WSL), plus Visual Studio Code. Basic DevOps awareness is enough for the Python work.
Before We Start
This step gives you a clear operational target before any hands-on work begins. Your analyzer will inspect sample.log to produce a severity summary for quick log health checks.
Set Up Python in WSL
Your log analyzer needs a Linux Python interpreter before it can inspect sample.log.
A project-specific virtual environment keeps future dependencies separate from Ubuntu's system interpreter. A WSL workspace gives Visual Studio Code access to that isolated Linux setup.
In this step, get ready to:
- Verify Ubuntu's default Python 3 runtime.
- Open the project directory through WSL in Visual Studio Code.
- Create and select the project's virtual environment.
Verify Python in Ubuntu
Ubuntu's system Python supports operating-system tools. Your project environment builds on that interpreter while keeping project dependencies inside its own folder.
- Press the Windows key to open the search bar.
- Type Ubuntu into the search bar.
- Select Ubuntu to open its terminal.
- Check Ubuntu's default Python interpreter by running this command:
python3 --version
What does this command check?
The python3 --version command asks Ubuntu's default Python 3 executable to identify its installed version.
Ubuntu manages this system interpreter for the installed release. Keep it available because Ubuntu tooling can depend on it.
✔️ I see a Python 3 version
Your Linux interpreter is ready. You now have the runtime that creates the project environment.
- Keep the Ubuntu terminal open for the project setup.
ⓧ Command not found
Ubuntu needs its complete default Python runtime before the project can create a virtual environment.
- Install Ubuntu's complete default Python runtime by running this command:
sudo apt install -y python3-full
What does this command install?
This installs Ubuntu's distro-default interpreter. It also adds the complete class library plus virtual-environment support.
Ubuntu may ask you to authenticate before the installation begins. Complete the terminal prompt to continue.
- Rerun the Python version check with this command:
python3 --version
Why run the check again?
This second check confirms that Ubuntu can now find the installed Python 3 interpreter.
You should now see a Python 3 version number in the terminal.
Installation did not complete?
Confirm that the terminal belongs to Ubuntu. Complete any authentication prompt before retrying the installation.
If package installation still fails, help me diagnose the Ubuntu installation problem.
Open the project through WSL
The project directory gives every script a predictable Linux location. Opening that directory through WSL makes Visual Studio Code use Ubuntu's files plus Ubuntu's tools.
- Create ~/python/devops-log-analyzer by running these commands:
mkdir -p ~/python/devops-log-analyzer
cd ~/python/devops-log-analyzer
What do these commands do?
The mkdir -p command creates the project directory plus any missing parent directory.
The cd command moves the terminal into ~/python/devops-log-analyzer.
- Confirm the terminal is inside the project directory by running:
pwd
What does this command show?
The pwd command prints the terminal's current directory. This confirms where later files get created.
You should see a path ending in /python/devops-log-analyzer.
- Open the current project directory in a WSL-connected Visual Studio Code window by running:
code .
What does this command open?
The code . command opens the current folder in Visual Studio Code. The WSL extension connects the editor to Ubuntu.
The first connection can install Visual Studio Code Server inside WSL. Follow any displayed connection prompt so the workspace can finish opening.
You should see devops-log-analyzer in the Explorer sidebar. The lower-left status area should show a WSL connection.
- Select the Extensions icon in the Activity Bar.
- Search for WSL in the Extensions view.
- Select the WSL extension published by Microsoft.
- Select Install if the extension page offers that action.
- Search for Python in the Extensions view.
- Select the Python extension published by Microsoft.
- Select Install in WSL if the extension page offers that action.
- Confirm that both extension pages show an installed state for this workspace.
WSL indicator or extensions missing?
Return to the Ubuntu terminal inside ~/python/devops-log-analyzer. Retry the folder-opening command after the WSL extension finishes installing.
If the Python extension only appears under local extensions, use its WSL installation action. Help me connect Visual Studio Code extensions to WSL.
Create the virtual environment
The .venv directory gives this project its own Python environment. Activating it makes terminal commands use the project interpreter.
- Return to the Ubuntu terminal from earlier.
- Create the .venv environment by running this command:
python3 -m venv .venv
What does this command create?
Python's venv module creates an isolated environment inside .venv.
The environment contains a project-specific Python executable. Future project dependencies stay separate from Ubuntu's system interpreter.
- Activate the new environment by running this command:
source .venv/bin/activate
What does activation change?
Activation updates the current terminal session so python3 resolves to the executable inside .venv.
Your terminal prompt should now include the environment name.
Virtual environment creation failed?
Missing virtual-environment support can stop .venv from being created. Use the complete Python installation path from the first substep before retrying the creation command.
If activation fails, confirm that the terminal is inside ~/python/devops-log-analyzer. Help me fix the virtual environment setup.
- Return to the WSL-connected Visual Studio Code window.
- Press F1 to open the Command Palette.
- Enter Python: Select Interpreter.
- Select the interpreter whose path ends in /devops-log-analyzer/.venv/bin/python3.
Before you run the final check, where do you expect Ubuntu to find python3 now that the environment is active?
- Reveal the active Python path by running this command in the Ubuntu terminal:
which python3
What does this path prove?
The which python3 command shows which executable the current terminal uses. A path inside .venv proves that environment isolation is active.
You should see a path ending in /devops-log-analyzer/.venv/bin/python3. That is the environment ready for your analyzer.
Still seeing the system Python path?
- Activate .venv again in the same Ubuntu terminal.
- Repeat the interpreter selection in the WSL-connected Visual Studio Code window.
- Rerun the path check after both environments point to .venv.
If the path still points outside the project, help me trace which Python interpreter WSL is using.
Your isolated Python workspace is ready. Next up, you will create the sample log and make the analyzer print its first real records.
Read the Raw Log
Your isolated Python environment is ready inside WSL. Now you can give the analyzer real application data to read.
A log file is stored text until a Python loop opens it. Iterating over its records creates the analyzer's first visible output.
In this step, get ready to:
- Create a sample log containing six application records.
- Read each record with a file loop.
- Run the analyzer to print all six records.
Create the sample log
The sample log gives the analyzer a fixed input to read. It includes one incomplete record that remains visible during the first run.
- In the VS Code file sidebar, select the new-file icon beside devops-log-analyzer.
- Enter sample.log as the filename.
- Fill sample.log with the six records by copying the content below:
2026-09-29T09:00:00Z INFO api started
2026-09-29T09:02:00Z WARNING disk usage reached 82 percent
BROKEN LINE
2026-09-29T09:03:00Z ERROR database connection failed
2026-09-29T09:04:00Z INFO retry started
2026-09-29T09:05:00Z ERROR retry failed
How is each record shaped?
- The opening value records the timestamp for a complete event.
- The next value records its severity as INFO, WARNING, or ERROR.
- The remaining text describes what happened.
- The BROKEN LINE record contains only two fields. It represents imperfect input that a real log analyzer must eventually handle.
- Save sample.log.
- Count the records shown in the editor.
You should count six records. The third record is BROKEN LINE.
Your analyzer now has ordinary records plus one imperfect record to process.
Missing a sample record?
Compare the editor with the reference tab below. Make sure BROKEN LINE sits between the WARNING record and the first ERROR record.
Help me check my sample.log file.
✔️ Awesome, I've got everything!
Your six-record sample log is saved and ready for the analyzer.
ⓧ I'd like to double check the full code
2026-09-29T09:00:00Z INFO api started
2026-09-29T09:02:00Z WARNING disk usage reached 82 percent
BROKEN LINE
2026-09-29T09:03:00Z ERROR database connection failed
2026-09-29T09:04:00Z INFO retry started
2026-09-29T09:05:00Z ERROR retry failed
Read every record with a loop
A context manager keeps the file open while the indented block runs. The loop then handles one record at a time.
- In the VS Code file sidebar, select the new-file icon beside devops-log-analyzer.
- Enter log_analyzer.py as the filename.
- Fill log_analyzer.py with the file-reading loop by copying the code below:
with open("sample.log", encoding="utf-8") as log_file:
for line in log_file:
print(line.strip())
How does the reader work?
- The open("sample.log", encoding="utf-8") call connects the script to the sample log using a defined text encoding.
- The log_file variable holds the opened file while the block runs.
- The with statement closes the file after the block finishes. This also happens if processing encounters a problem.
- The for line in log_file loop places one record at a time into the line variable.
- The line.strip() method removes the trailing line break before print() displays the record.
- Save log_analyzer.py.
Before you run the reader, do you expect it to stop at the incomplete record or print every line?
- In the activated .venv terminal from earlier, print the log by running this command:
python3 log_analyzer.py
You'll see six lines in the same order as sample.log. The output includes BROKEN LINE.
You have your first visible analyzer result. The script reads the whole file without dropping the imperfect record.
This raw view proves that file handling works. It still leaves the operator to count severities by hand.
Don't see all six records?
Check that the activated terminal is still inside ~/python/devops-log-analyzer. Confirm that sample.log and log_analyzer.py appear in the same VS Code file sidebar.
Check the indentation in log_analyzer.py. The for line sits inside the with block. The print line sits inside the loop.
Help me debug why my raw log reader does not print all six records.
✔️ Awesome, I've got everything!
Your reader is saved and prints every record from the sample log.
ⓧ I'd like to double check the full code
with open("sample.log", encoding="utf-8") as log_file:
for line in log_file:
print(line.strip())
Your file reader works. Next, you'll turn these raw records into severity counts.
Parse the Log and Observe the Failure
Your Python analyzer can already read all six records from sample.log. Operators still need a summary that shows how many records belong to each severity.
A first parser assumes every record has the same shape. This step tests that assumption against imperfect input.
In this step, get ready to:
- Create zeroed counters for the allowed severity levels.
- Parse each record into three fields.
- Run the naive parser to expose its perfect-input assumption.
Define the allowed severities and counters
A tuple stores the three severity labels your analyzer accepts. A dictionary maps each label to a count that can change while the file is processed.
- In log_analyzer.py, replace its current contents with the code below:
LEVELS = ("INFO", "WARNING", "ERROR")
counts = {level: 0 for level in LEVELS}
with open("sample.log", encoding="utf-8") as log_file:
for line in log_file:
print(line.strip())
for level in LEVELS:
print(f"{level}: {counts[level]}")
How do these values work?
- The LEVELS tuple defines the accepted severity labels in one place.
- The counts dictionary starts every severity at 0.
- The file loop still displays each raw record.
- The final loop displays the current value for every severity.
- Save log_analyzer.py.
- Check the counter setup by running this command:
python3 log_analyzer.py
What should you see?
You should see all six raw records followed by INFO: 0, WARNING: 0, and ERROR: 0.
Good. Your script now has counters that are ready to receive parsed severity values.
Counters missing from the output?
Check that the final for level in LEVELS: loop starts at the left edge of log_analyzer.py. An extra indent can place it inside the file loop.
Confirm that counts is defined before the file opens.
Help me debug the missing severity counters.
Split each record and update its count
String splitting turns one log record into separate values. Limiting the split to two breaks keeps the remaining message together even when it contains spaces.
- In log_analyzer.py, find this line:
print(line.strip())
What does the current line do?
The current line removes surrounding whitespace before displaying the record. It keeps the timestamp, severity, and message inside one string.
- Replace that line with these two lines:
timestamp, level, message = line.strip().split(maxsplit=2)
counts[level] += 1
What does this parsing code do?
- The split(maxsplit=2) call produces up to three pieces from each stripped record.
- Variable unpacking assigns those pieces to timestamp, level, and message.
- The counts[level] lookup finds the counter whose key matches the parsed severity.
- The += 1 operation increases that counter for the current record.
- Save log_analyzer.py.
Run the naive parser
The parser now applies the same three-field rule to every record. The next run tests that rule against the unchanged file.
- Predict whether every record can supply exactly three values.
- Test your prediction by running this command:
python3 log_analyzer.py
The failure is the lesson
You should see a ValueError traceback when the parser reaches BROKEN LINE. The complete severity summary does not appear.
That crash is intentional. The two-field record cannot fill the three variables required by the unpacking assignment.
- Read the final exception line at the bottom of the traceback.
- Trace upward to the unpacking assignment in log_analyzer.py.
- Return to sample.log from earlier.
- Locate the BROKEN LINE record that supplied only two fields.
No traceback appeared?
Confirm that sample.log still contains BROKEN LINE as its third record.
Check that the file loop uses the three-variable unpacking assignment before updating counts[level].
Help me reproduce the expected malformed-record failure.
At this point, log_analyzer.py should match the deliberately naive parser below.
✔️ Awesome, I've got everything!
Your file matches the naive parser that exposes malformed input through a visible failure.
ⓧ I'd like to double check the full code
LEVELS = ("INFO", "WARNING", "ERROR")
counts = {level: 0 for level in LEVELS}
with open("sample.log", encoding="utf-8") as log_file:
for line in log_file:
timestamp, level, message = line.strip().split(maxsplit=2)
counts[level] += 1
for level in LEVELS:
print(f"{level}: {counts[level]}")
Why does this version fail?
This version assumes every record produces exactly three values. The unchanged malformed record proves that the assumption is unsafe.
You have exposed the parser's fragile assumption with a real traceback. Next, you will replace that crash with validation that keeps the analyzer running.
Make the Analyzer Resilient
The last run proved your analyzer can split perfect records. It also stopped at BROKEN LINE before the summary completed.
Real logs often contain incomplete records. This step adds validation so the analyzer can count malformed input without abandoning valid records.
In this step, get ready to:
- Separate line parsing into parse_log_line(line).
- Build analyze_log(log_file) to keep processing after invalid input.
- Print the final counts with print_summary(report).
Validate each log record
A function gives parsing one named responsibility. parse_log_line(line) returns a dictionary for a valid record or None for a rejected one.
- Return to log_analyzer.py in the Visual Studio Code workspace from earlier.
- Find LEVELS = ("INFO", "WARNING", "ERROR") near the top of the file.
- Replace every line below LEVELS with this parser:
def parse_log_line(line):
parts = line.strip().split(maxsplit=2)
if len(parts) != 3:
return None
timestamp, level, message = parts
if level not in LEVELS:
return None
return {
"timestamp": timestamp,
"level": level,
"message": message,
}
What Does This Code Do?
- The parts variable holds up to three pieces from the stripped line. Limiting the split preserves spaces inside the message.
- The length check protects the three-variable unpacking. A record with fewer or more fields returns None.
- The severity check accepts only values listed in LEVELS. An unknown severity also returns None.
- A valid record becomes a dictionary containing timestamp, level, and message.
Each return sends the parsing result back to the code that called the function. The caller can then decide whether to count or reject the record.
Analyze every record safely
The analyze_log(log_file) function owns the loop and its changing counters. Each invalid entry increases malformed_lines.
The continue statement advances directly to the next record. One rejected line no longer ends the entire analysis.
- Place your cursor below the closing brace of parse_log_line(line).
- Add analyze_log(log_file) by pasting this code:
def analyze_log(log_file):
counts = {level: 0 for level in LEVELS}
malformed_lines = 0
with open(log_file, encoding="utf-8") as file:
for line in file:
entry = parse_log_line(line)
if entry is None:
malformed_lines += 1
continue
counts[entry["level"]] += 1
return {
"source": log_file,
"counts": counts,
"malformed_lines": malformed_lines,
}
How Does the Analyzer Stay Running?
- The counts dictionary starts each allowed severity at zero.
- The malformed_lines variable tracks records rejected by the parser.
- The file loop sends one line at a time to parse_log_line(line).
- A valid entry updates the counter selected by entry["level"].
The final return packages the source path, severity counts, and malformed count into one report.
- Invoke the analyzer by adding this line below analyze_log(log_file):
report = analyze_log("sample.log")
Why Create the Report Now?
This call processes every record in sample.log. The returned dictionary is stored in report for the summary function.
- Save log_analyzer.py.
Before you run the script, predict whether BROKEN LINE will stop the process this time. Hold that prediction as you test the new control flow.
- Test the analyzer from the activated terminal by running:
python3 log_analyzer.py
What Should Happen?
The command processes all six records. You should return to the shell prompt without a ValueError traceback.
That is the crash removed. The malformed record now reaches the rejection path instead of stopping the script.
Still Seeing a Traceback?
Check that the old top-level unpacking code was removed from log_analyzer.py. The only unpacking line should now sit inside parse_log_line(line) after the length check.
Confirm that continue is indented inside the invalid-entry condition. It must run before the dictionary counter is accessed.
Help me compare my parser and analyzer with the expected indentation.
Print and trace the resilient result
The analyzer now produces a complete report dictionary. print_summary(report) converts that state into counts an operator can read.
- Find report = analyze_log("sample.log") at the bottom of log_analyzer.py.
- Replace that line with the summary function and its two calls:
def print_summary(report):
print("Log summary")
for level in LEVELS:
print(f"{level}: {report['counts'][level]}")
print(f"Malformed lines: {report['malformed_lines']}")
report = analyze_log("sample.log")
print_summary(report)
How Does the Summary Work?
- The severity loop reads each counter from report["counts"] in the order defined by LEVELS.
- The final print reads malformed_lines from the same report.
- The first call analyzes sample.log. The second call displays the returned report.
- Save log_analyzer.py.
Use the tabs below to compare the finished file before the final run.
✔️ Awesome, I've got everything!
Your parser, analyzer, and summary functions are ready. Confirm that log_analyzer.py is saved.
ⓧ I'd like to double check the full code
LEVELS = ("INFO", "WARNING", "ERROR")
def parse_log_line(line):
parts = line.strip().split(maxsplit=2)
if len(parts) != 3:
return None
timestamp, level, message = parts
if level not in LEVELS:
return None
return {
"timestamp": timestamp,
"level": level,
"message": message,
}
def analyze_log(log_file):
counts = {level: 0 for level in LEVELS}
malformed_lines = 0
with open(log_file, encoding="utf-8") as file:
for line in file:
entry = parse_log_line(line)
if entry is None:
malformed_lines += 1
continue
counts[entry["level"]] += 1
return {
"source": log_file,
"counts": counts,
"malformed_lines": malformed_lines,
}
def print_summary(report):
print("Log summary")
for level in LEVELS:
print(f"{level}: {report['counts'][level]}")
print(f"Malformed lines: {report['malformed_lines']}")
report = analyze_log("sample.log")
print_summary(report)
What Does This Reference Show?
This reference matches the complete resilient log_analyzer.py for this step. Compare its function order and indentation with your saved file.
Before the final run, predict how the six records will be divided between the four counters. Keep your prediction in mind as the summary appears.
- Run the completed resilient analyzer from the activated terminal:
python3 log_analyzer.py
What Should You See?
You should see Log summary followed by these four results:
- INFO: 2.
- WARNING: 1.
- ERROR: 2.
- Malformed lines: 1.
A valid ERROR record becomes an entry dictionary. Its level selects the counter that increases.
BROKEN LINE produces two parts. The parser returns None, so the malformed counter increases before continue moves to the next record.
You have turned the original crash into an operational signal. Every valid record now contributes to the finished summary.
Counts Do Not Match?
Keep all six lines in sample.log, including BROKEN LINE. Removing that record makes the malformed count zero.
Check that the valid counter uses counts[entry["level"]]. Using the old counts[level] line bypasses the parsed entry.
Help me trace why my severity or malformed counts differ from the expected result.
Your analyzer now survives imperfect logs and reports their quality. Next, you will accept runtime file paths and save the same report as structured JSON.
Build the CLI and JSON Reporter
Your analyzer now survives malformed records. Operators still have to edit the script to choose a log file.
A reusable command-line interface accepts paths when the program starts. A JSON report gives the next automation step structured data.
Focused file error handling converts operating system failures into readable messages. A controlled process exit status tells the shell whether the command succeeded.
In this step, get ready to:
- Accept the log path plus JSON output path as command-line inputs.
- Handle file errors with a readable message plus a controlled status.
- Generate a structured report from the resilient analyzer.
Add the CLI imports and JSON writer
Python's standard library already contains the modules needed for command-line parsing, JSON serialization, and shell status handling. Importing them keeps this project focused on Python fundamentals.
- In the log_analyzer.py tab from earlier, place the cursor above LEVELS.
- Add the three standard-library imports by pasting this code:
import argparse
import json
import sys
What Do These Imports Add?
- The argparse module converts command-line input into named values for your program.
- The json module serializes the report dictionary into JSON.
- The sys module passes the result from main() back to the calling shell.
- Save log_analyzer.py.
- Click Run Python File in the top-right corner of the editor.
You'll see the four existing counts without a traceback. This confirms the imports load successfully inside your selected virtual environment.
Does the Script Stop at an Import?
Check that each import sits above LEVELS. Confirm that each module name matches the code exactly.
Help me fix the import failure in my Python log analyzer.
The analyzer already returns one dictionary containing the source path, severity counts, and malformed count. The new writer serializes that dictionary directly into an output file.
- Place the cursor below the final line of print_summary(report).
- Add the JSON writer by pasting this function:
def save_report(report, output_file):
with open(output_file, "w", encoding="utf-8") as file:
json.dump(report, file, indent=2)
How Does the JSON Writer Work?
- The output_file parameter holds the destination path supplied by the operator.
- The file opens in "w" mode so Python can write the report.
- The json.dump() call converts the report dictionary into JSON.
- The indent=2 setting makes the generated file easier to read.
- Save log_analyzer.py.
- Click Run Python File again.
You'll see the severity summary complete without a traceback. This confirms Python can define the JSON writer alongside the existing analyzer.
Seeing a Syntax Error Near the Writer?
Check that save_report() starts at the left edge of the file. Keep the two statements inside it indented by four spaces.
Help me fix the save_report function.
Connect runtime inputs and file errors
A parser defines the values an operator can provide when the script starts. The resulting namespace connects those command-line values to Python names inside main().
- Place the cursor below save_report().
- Add the command-line parser by pasting this function:
def build_parser():
parser = argparse.ArgumentParser(
description="Analyze a simple application log."
)
parser.add_argument(
"log_file",
help="Path to the log file to analyze.",
)
parser.add_argument(
"--output",
default="report.json",
help="Path for the JSON report.",
)
return parser
What Does the Parser Define?
- The log_file argument is required because the analyzer needs an input path.
- The --output option lets an operator choose the report path.
- The default output path is report.json.
- Returning parser gives main() access to the completed command-line definition.
- Save log_analyzer.py.
- Click Run Python File to check the new function.
You'll see the existing summary complete again. The successful run confirms the parser definition has valid Python syntax.
Does the Parser Trigger an Indentation Error?
Keep each parser.add_argument() call inside build_parser(). Align return parser with the first parser assignment.
Help me fix the build_parser function.
The main() function coordinates parsing, analysis, file writing, and terminal output. A focused OSError handler catches file access failures without hiding unrelated programming mistakes.
- Delete the direct-run line that starts with report = analyze_log at the bottom of log_analyzer.py.
- Delete print_summary(report) directly below it.
- Add the final program flow by pasting this code at the bottom of the file:
def main():
parser = build_parser()
args = parser.parse_args()
try:
report = analyze_log(args.log_file)
save_report(report, args.output)
except OSError as error:
print(f"Could not process a file: {error}")
return 1
print_summary(report)
print(f"JSON report written to {args.output}")
return 0
if __name__ == "__main__":
sys.exit(main())
How Does the CLI Flow Work?
- The parse_args() call reads the command-line input into args.
- The args.log_file value becomes the input path for analyze_log().
- The args.output value becomes the destination for save_report().
- The try block protects both file operations.
- The except OSError block prints a readable file error before returning status 1.
- A successful run returns status 0.
- The main guard sends that status to the shell through sys.exit(main()).
- Save log_analyzer.py.
- Double-check the completed file with the tabs below.
✔️ Awesome, I've got everything!
Great. Your saved script now contains the final core-project code.
ⓧ I'd like to double check the full code
import argparse
import json
import sys
LEVELS = ("INFO", "WARNING", "ERROR")
def parse_log_line(line):
parts = line.strip().split(maxsplit=2)
if len(parts) != 3:
return None
timestamp, level, message = parts
if level not in LEVELS:
return None
return {
"timestamp": timestamp,
"level": level,
"message": message,
}
def analyze_log(log_file):
counts = {level: 0 for level in LEVELS}
malformed_lines = 0
with open(log_file, encoding="utf-8") as file:
for line in file:
entry = parse_log_line(line)
if entry is None:
malformed_lines += 1
continue
counts[entry["level"]] += 1
return {
"source": log_file,
"counts": counts,
"malformed_lines": malformed_lines,
}
def print_summary(report):
print("Log summary")
for level in LEVELS:
print(f"{level}: {report['counts'][level]}")
print(f"Malformed lines: {report['malformed_lines']}")
def save_report(report, output_file):
with open(output_file, "w", encoding="utf-8") as file:
json.dump(report, file, indent=2)
def build_parser():
parser = argparse.ArgumentParser(
description="Analyze a simple application log."
)
parser.add_argument(
"log_file",
help="Path to the log file to analyze.",
)
parser.add_argument(
"--output",
default="report.json",
help="Path for the JSON report.",
)
return parser
def main():
parser = build_parser()
args = parser.parse_args()
try:
report = analyze_log(args.log_file)
save_report(report, args.output)
except OSError as error:
print(f"Could not process a file: {error}")
return 1
print_summary(report)
print(f"JSON report written to {args.output}")
return 0
if __name__ == "__main__":
sys.exit(main())
Run the CLI and inspect the report
The script now receives both paths when it starts. This final check proves one command can produce a terminal summary plus a machine-readable file.
Before you run it, what counts do you expect the terminal and JSON report to contain?
- Return to the activated .venv terminal from earlier.
- Run the completed CLI with an explicit input path plus output path:
python3 log_analyzer.py sample.log --output report.json
You'll see INFO: 2.
You'll see WARNING: 1.
You'll see ERROR: 2.
You'll see Malformed lines: 1 without a traceback.
The final terminal line confirms that the JSON report was written to report.json.
Does the CLI Stop Before the Summary?
Confirm that your activated terminal is inside ~/python/devops-log-analyzer. Check that sample.log appears beside log_analyzer.py.
Help me debug the CLI run.
- Select report.json in the Explorer sidebar.
- Compare the generated contents with this report:
{
"source": "sample.log",
"counts": {
"INFO": 2,
"WARNING": 1,
"ERROR": 2
},
"malformed_lines": 1
}
How Does the Report Map to Python?
- The source field comes from the log_file value passed into analyze_log().
- The counts object comes from the severity dictionary updated inside the file loop.
- The malformed_lines field records the rejected BROKEN LINE entry.
- The JSON structure preserves the same values shown in the terminal summary.
You now have one command that turns an imperfect log file into human-readable triage plus structured automation data. That is the core analyzer working from input path to generated report.
Does the JSON Report Differ?
Confirm that save_report(report, args.output) sits inside the try block. Check that json.dump() receives report as its first argument.
Help me compare the JSON report with my Python dictionary.
Secret mission
Add a CI-Friendly Failure Threshold
Extend your analyzer with an operator-defined ERROR threshold. The command will return a process status that a CI/CD pipeline can use to pass or fail a job.
Clean Up Your Resources
Clean Up Your Resources
This project has no cloud resources or ongoing costs. Choose whether to keep the ~/python/devops-log-analyzer folder, pause by closing your workspace, or delete the project files.
Resources you used:
- The ~/python/devops-log-analyzer directory containing log_analyzer.py, sample.log, report.json, and the .venv virtual environment.
Keep everything running
No action is needed. Choose this if you want to reuse the analyzer or continue practising Python automation.
- Your files remain in ~/python/devops-log-analyzer.
- Your .venv environment remains available for future work.
- Your analyzer remains ready to process other log files from the terminal.
Pause - I'll come back to this later
Stop the active shell session while keeping every project file. You can return to the same folder later.
- Close the terminal inside your existing Visual Studio Code workspace.
- Close the Visual Studio Code window.
Closing the terminal ends the active virtual environment session. Your files remain unchanged inside ~/python/devops-log-analyzer.
Delete - I don't want to use this again
Deleting the project folder is permanent. Your Python script, sample log, JSON report, and virtual environment all disappear together.
- Move outside the project folder and delete it by running these commands:
cd ~/python
rm -rf devops-log-analyzer
What Do These Commands Do?
The first command moves the shell outside the folder being removed. The second command deletes the complete project directory.
- Confirm the project directory is gone by running this command:
ls ~/python
What Should You See?
The devops-log-analyzer name should be absent from the directory listing. That confirms every project artifact has been removed.
- Close the current Visual Studio Code window.
Nice Work!
Nice Work!
You made it! Your Python log analyzer now converts imperfect application records into operational signals. It keeps malformed input visible while producing a terminal summary plus a machine-readable JSON report.
You've learned how to:
- Read sample.log one record at a time with file handling. Convert each record into severity counts with loops plus dictionaries.
- Protect the analyzer from malformed records with validation. Report file failures through a focused OSError handler.
- Accept runtime paths through a reusable command-line interface. Serialize the analysis into report.json for later automation.
- Secret Mission: Connected an ERROR threshold to a CI/CD process status so an automated job can evaluate log health.
Ready to quiz yourself?