Parse Logs and Extract Indicators
Turn raw logs into structured evidence with regular expressions, JSON, CSV, and careful de-duplication.
By the end, you’ll be able to…
- Explain why log parsing must preserve context and timestamps.
- Use Python regular expressions to extract IPs, domains, URLs, and hashes.
- Aggregate and de-duplicate indicators without losing the source event.
- Produce a stable JSON or CSV report that another analyst can review.
01Logs Are Evidence, Not Just Text
A log line is a record of something that happened. The message is only part of the value. The timestamp, host, service, severity, user, source address, and event ID give the message meaning. If you extract an IP address without the event that produced it, you cannot tell whether it is an attacker, a health checker, or a misconfigured internal service.
Different log formats require different parsers. Syslog has a header and a free-form message. JSON logs have named fields. Web server logs often follow the Common Log Format. Windows event logs are structured records. Application logs may be anything the developer chose. Before writing a regex, inspect several examples and identify which fields are stable and which are free text.
Parsing is lossy by design. You decide which fields matter and which you discard. Document that decision. If a field is missing, record it as unknown instead of inventing a value. If a line fails to parse, keep the line number and the reason. The report should make the gaps visible.
02Regular Expressions for Indicators
A regular expression describes a pattern in text. In Python, the re module compiles patterns and searches strings. Use raw strings such as r'\d+' so backslashes are passed through to the regex engine. Anchor patterns when you need a whole string, and use word boundaries when a substring match would be misleading.
Indicators are not proof of compromise. An IP address may be shared, a domain may be compromised rather than malicious, and a file hash may match a known-good tool. Enrichment adds context: reputation, WHOIS, passive DNS, sandbox results, and internal asset ownership. Never block an indicator automatically without a human decision and a rollback path.
Extract the smallest useful set of indicators and keep the association with the source event. A URL can contain credentials, tokens, or personal data. Redact or hash sensitive values before sharing. Prefer parsed URL components over a raw string when you need the hostname. Normalise case for domains, but do not normalise case in file paths or passwords.
03Aggregate Without Losing the Story
Security analysis often needs aggregates: failed logins by source, requests by status code, domains contacted by a host, or files seen across endpoints. Aggregation reduces noise, but it can also hide the first occurrence and the sequence of events. Keep both the summary and a sample of the underlying records.
Use dictionaries or Counter for counts. Track the first and last seen timestamp for each indicator. Store the source file and line number so a reviewer can find the original event. If you combine indicators from multiple sources, add a source column rather than merging away provenance. When you sort, make the order deterministic so two runs produce the same report.
Output formats should match the audience. JSON is good for machines and further processing. CSV is good for spreadsheets and quick review. Markdown is good for a human-readable summary. Whatever you choose, include a schema or header, a generated-at timestamp, the input file names, and the tool version. Reproducibility is a security feature.
04Build for the Next Analyst
A script that only you can run is a liability during an incident. Give it a name that says what it does, a short usage message, and an example command. Accept --input and --output paths. Exit with a non-zero status when the input is missing or unreadable. Print progress to stderr and the report to a file so logs and results do not mix.
Add a small test fixture. A fixture is a miniature, non-sensitive sample that represents the real format. Test the parser against it, then test a malformed line, an empty file, and a duplicate record. If the script makes network requests, mock them in tests. If it writes files, use a temporary directory and clean up.
Finally, document the assumptions. Which timestamp format? Which time zone? What counts as a failure? How are duplicates handled? What is deliberately out of scope? This documentation is what lets someone else trust the output. It also protects you when the data changes and the script needs to be updated.
The ideas worth keeping.
- Logs are evidence: keep timestamps, source, and event context with every extracted indicator.
- Regular expressions find candidates; parsers and validators decide whether they are usable.
- Aggregate for signal but preserve provenance and a sample of raw events.
- Stable JSON or CSV output, deterministic ordering, and documented assumptions make analysis reproducible.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Extract and validate IPs
Write a Python script that finds candidate IPv4 addresses in a text file, validates them with ipaddress.ip_address, and prints a sorted list of unique public addresses. Exclude private, loopback, link-local, and multicast addresses.
Explore a worked solution
import ipaddress
import re
from pathlib import Path
pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')
text = Path('sample.log').read_text(encoding='utf-8')
unique = set()
for match in pattern.findall(text):
try:
address = ipaddress.ip_address(match)
except ValueError:
continue
if address.is_global:
unique.add(str(address))
print('\n'.join(sorted(unique)))Regex finds candidates; ipaddress validates them. is_global excludes private, loopback, link-local, multicast, and other non-public ranges.
Exercise 2: Produce a triage summary
Given a list of dictionaries with 'src' and 'event' fields, write a function that returns only the sources with more than three failed login events, sorted by count descending. Include the first and last timestamp if present.
Explore a worked solution
from collections import defaultdict
def suspicious_sources(events, threshold=3):
summary = defaultdict(lambda: {'count': 0, 'first': None, 'last': None})
for event in events:
if event.get('event') != 'login_failed':
continue
src = event.get('src', 'unknown')
row = summary[src]
row['count'] += 1
ts = event.get('ts')
if ts:
row['first'] = min(filter(None, [row['first'], ts]))
row['last'] = max(filter(None, [row['last'], ts]))
return sorted(
((src, row) for src, row in summary.items() if row['count'] > threshold),
key=lambda item: item[1]['count'],
reverse=True,
)The function filters to the event of interest, aggregates per source, and returns a deterministic, sorted result. A real script would parse timestamps into datetime objects for correct ordering across time zones.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.