Ravindra BagaleCourses & study guides मराठी

Chapter 95: Logging with Loki, Elastic Stack and CloudWatch

DevOps

95.19 Entirely local lab — synthetic Python logging and parsing

Story (fictional teaching scenario). Rutuja from Satara and Daniel from Lisbon create six invented bakery events. They can verify safe field selection and arithmetic without collecting anyone’s real logs.

Entirely local lab — synthetic Python logging and parsing
Entirely local lab — synthetic Python logging and parsing

Why

A small deterministic exercise makes timestamp and parsing mistakes visible without a heavy logging stack or cloud bill.

What

  • This local teaching model uses Python’s standard library only.
  • A formatter converts a Python logging record into output text.
  • A unit test checks the small program’s behaviour, not production redaction or engine compatibility.
  • The allowlist supports only this fictional schema; no real personal or sensitive values may be entered.

How

  1. Create an empty local practice folder.

  2. Save loglab.py and test_loglab.py exactly as shown.

  3. Run python3 -m unittest -v, then python3 loglab.py.

  4. Generate only the optional synthetic JSONL file in this lab folder.

  5. Do not install a collector, Loki, Elasticsearch or AWS client; none is needed.

Example 1: Complete loglab.py

"""SYNTHETIC classroom model. NOT a Loki/Elastic/CloudWatch engine or security product.
No network, environment reading or real log collection. Fake fields only.
"""
import json,logging,io,re
from datetime import datetime,timezone,timedelta
from collections import Counter
LEVELS={'INFO','WARN','ERROR'}

def instant(text):
    dt=datetime.fromisoformat(text.replace('Z','+00:00'))
    if dt.tzinfo is None or dt.utcoffset() is None:
        raise ValueError('explicit timezone required')
    return dt

def safe_event(raw):
    # This narrow allowlist is designed for this fake schema only.
    # Do NOT treat it as a general PII/credential detector.
    ts=instant(raw['ts']).astimezone(timezone.utc)
    if raw['service'] not in {'bakery-api','bakery-worker'}:
        raise ValueError('unknown fictional service')
    if raw['level'] not in LEVELS:raise ValueError('unknown severity')
    if not re.fullmatch(r'req-demo-[0-9]{3}',raw['request_id']):
        raise ValueError('synthetic request ID required')
    if type(raw['status']) is not int or not 100<=raw['status']<=599:
        raise ValueError('invalid status')
    if type(raw['latency_ms']) is not int or raw['latency_ms']<0:
        raise ValueError('invalid duration')
    return {'ts':ts.isoformat().replace('+00:00','Z'),'service':raw['service'],
            'level':raw['level'],'request_id':raw['request_id'],
            'status':raw['status'],'latency_ms':raw['latency_ms']}

def parse(line):
    raw=json.loads(line)
    if not isinstance(raw,dict):raise ValueError('object required')
    return safe_event(raw)

class SafeFormatter(logging.Formatter):
    def format(self,record):
        # Ignore free-form message/exception data; publish only validated demo fields.
        return json.dumps(safe_event(record.event),sort_keys=True)

def emit(raw):
    buf=io.StringIO();handler=logging.StreamHandler(buf)
    handler.setFormatter(SafeFormatter())
    logger=logging.Logger('synthetic-classroom',level=logging.INFO)
    logger.propagate=False;logger.addHandler(handler)
    logger.info('synthetic event',extra={'event':raw})
    handler.close()
    return buf.getvalue().strip()

def fixture():
    specs=[('INFO',200,20),('INFO',200,40),('WARN',429,200),
           ('ERROR',500,800),('ERROR',503,900),('INFO',200,30)]
    return [{'ts':f'2026-11-01T00:00:0{i}Z','service':'bakery-api',
             'level':level,'request_id':f'req-demo-{i:03}',
             'status':status,'latency_ms':latency,
             'private_note':'FICTIONAL_REMOVE'}
            for i,(level,status,latency) in enumerate(specs)]

def to_ist(text):
    return instant(text).astimezone(timezone(timedelta(hours=5,minutes=30))).isoformat()

def summarize(events):
    counts=Counter(e['level'] for e in events)
    return {'events':len(events),'errors':counts['ERROR'],
            'error_percent':round(100*counts['ERROR']/len(events),2) if events else 0.0,
            'mean_latency_ms':round(sum(e['latency_ms'] for e in events)/len(events),2) if events else 0.0}

def deduplicate(events):
    # Teaching key only; a real retry may share a request ID but be a distinct event.
    seen=set();out=[]
    for e in events:
        key=(e['ts'],e['request_id'],e['status'])
        if key not in seen:seen.add(key);out.append(e)
    return out

def join_stack(lines):
    # Only the artificial 'ERROR ' start rule is supported, not arbitrary stack formats.
    out=[]
    for line in lines:
        if line.startswith('ERROR ') or not out:out.append(line)
        else:out[-1]+='\n'+line
    return out

if __name__=='__main__':
    events=[parse(emit(e)) for e in fixture()]
    print(json.dumps(summarize(events),sort_keys=True))
    print('First event in IST:',to_ist(events[0]['ts']))
  1. instant requires an explicit timezone and refuses naive timestamps.
  2. safe_event checks types and controlled values, returning only six approved fields.
  3. Unknown fields, including nested extras, are dropped rather than serialized.
  4. This does not guarantee that arbitrary real values inside allowed fields are safe. The request ID pattern and service list deliberately limit the lab to invented content.
  5. SafeFormatter ignores free-form message/exception text; it publishes validated demonstration fields only.
  6. emit creates an isolated in-memory logger, not a root logger or a real log collector.
  7. fixture creates six fixed events with one fake field to remove. No input file, environment or production log is read.
  8. to_ist converts explicit instants; summarize computes counts and arithmetic.
  9. deduplicate and join_stack are deliberately limited teaching rules, not general distributed-log correctness guarantees.

Example 2: Complete test_loglab.py

import unittest,json
from loglab import *
class LoggingTests(unittest.TestCase):
    def setUp(self):self.raw=fixture()[0]
    def test_six(self):self.assertEqual(len(fixture()),6)
    def test_schema(self):self.assertEqual(len(safe_event(self.raw)),6)
    def test_drop_unknown(self):self.assertNotIn('private_note',safe_event(self.raw))
    def test_nested_drop(self):
        self.raw['extra']={'private_note':'FICTIONAL_REMOVE'}
        self.assertNotIn('extra',safe_event(self.raw))
    def test_no_mutation(self):
        safe_event(self.raw);self.assertEqual(self.raw['private_note'],'FICTIONAL_REMOVE')
    def test_logging_redaction(self):self.assertNotIn('FICTIONAL_REMOVE',emit(self.raw))
    def test_roundtrip(self):self.assertEqual(parse(emit(self.raw)),safe_event(self.raw))
    def test_bad_json(self):
        with self.assertRaises(json.JSONDecodeError):parse('{broken')
    def test_no_array(self):
        with self.assertRaises(ValueError):parse('[]')
    def test_timezone_required(self):
        with self.assertRaises(ValueError):instant('2026-11-01T00:00:00')
    def test_ist(self):self.assertEqual(to_ist('2026-11-01T00:00:00Z'),'2026-11-01T05:30:00+05:30')
    def test_rollover(self):self.assertEqual(to_ist('2026-11-01T22:00:00Z'),'2026-11-02T03:30:00+05:30')
    def test_invalid_level(self):
        self.raw['level']='UNKNOWN'
        with self.assertRaises(ValueError):safe_event(self.raw)
    def test_boolean_status(self):
        self.raw['status']=True
        with self.assertRaises(ValueError):safe_event(self.raw)
    def test_negative_latency(self):
        self.raw['latency_ms']=-1
        with self.assertRaises(ValueError):safe_event(self.raw)
    def test_realish_id_rejected(self):
        self.raw['request_id']='not-a-demo-id'
        with self.assertRaises(ValueError):safe_event(self.raw)
    def test_summary(self):
        s=summarize([safe_event(x) for x in fixture()]);self.assertEqual(s,{'events':6,'errors':2,'error_percent':33.33,'mean_latency_ms':331.67})
    def test_empty(self):self.assertEqual(summarize([])['error_percent'],0.0)
    def test_duplicate(self):
        e=[safe_event(x) for x in fixture()];self.assertEqual(len(deduplicate(e+[e[0]])),6)
    def test_multiline(self):self.assertEqual(join_stack(['ERROR failed','  at demo.py:1','ERROR next']),['ERROR failed\n  at demo.py:1','ERROR next'])
if __name__=='__main__':unittest.main()

Example 3: Run the local tests and summary

  1. Read the command or request.
python3 -m unittest -v
python3 loglab.py
  1. Read the result.

Output (ACTUAL deterministic local Python; NOT a logging-stack integration)

Ran 20 tests
OK
{"error_percent":33.33,"errors":2,"events":6,"mean_latency_ms":331.67}
First event in IST:2026-11-01T05:30:00+05:30
  1. Line by line: The first command runs 20 deterministic tests. The second emits summary values, not the removed fictional field. Two of six events are ERROR, giving 33.33 percent. Latency sum 1990 divided by 6 is 331.67 milliseconds after rounding. The test suite actually passed locally. It does not validate LogQL, Elasticsearch, CloudWatch ingestion, distributed delivery or security controls.

Example 4: Optional local synthetic file only

  1. Read the command or request.
from pathlib import Path
from loglab import fixture, emit
Path("synthetic.jsonl").write_text("\n".join(emit(e) for e in fixture()) + "\n")
  1. Read the result.

Output (ACTUAL deterministic local Python; NOT a logging-stack integration)

A local synthetic.jsonl file contains six sanitized fictional JSON events.
  1. Line by line: The import uses the model saved above. fixture generates invented data. emit applies the narrow formatter. write_text writes only the named practice file; do not substitute a real system log path. This file was actually generated in the isolated chapter lab.

Ravindra Bagale's Tip

These tests prove Python behaviour, not a logging platform or a privacy certification.

Did you understand? Let us try it once more.