10
0
This repository has been archived on 2023-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
mongo-logger/tailer.py

55 lines
1.8 KiB
Python
Raw Normal View History

2021-06-30 14:41:07 +00:00
import argparse
import asyncio
import re
import os
import sys
from motor.motor_asyncio import AsyncIOMotorClient
from termcolor import colored
MONGO_URI = os.getenv("MONGO_URI")
if not MONGO_URI:
print("MONGO_URI not specified")
sys.exit(1)
db = AsyncIOMotorClient(MONGO_URI).get_default_database()
parser = argparse.ArgumentParser()
2021-07-05 12:44:44 +00:00
parser.add_argument("--include-container", action="append", default=[])
parser.add_argument("--exclude-container", action="append", default=[])
parser.add_argument("--exclude-host", action="append", default=[])
2021-06-30 14:41:07 +00:00
args = parser.parse_args()
2021-07-05 12:44:44 +00:00
2021-06-30 14:41:07 +00:00
async def main():
2021-07-05 12:44:44 +00:00
async with db.log.watch([{"$match": {"operationType": "insert"}}]) as stream:
2021-06-30 14:41:07 +00:00
print("Connected")
async for event in stream:
doc = event["fullDocument"]
host = doc.get("host", "-")
if host in args.exclude_host:
continue
container_name = doc.get("container_name", "/-")[1:]
if args.include_container and container_name not in args.include_container:
continue
if container_name in args.exclude_container:
continue
msg = doc.get("message")
if msg:
container_name = "system:%s" % doc.get("ident")
else:
msg = doc.get("log")
# TODO: Do this mangling in fluentd.conf
m = re.match("time=\".*?\" level=[a-z]+ msg=\"(.*?)\"", msg)
if m:
msg, = m.groups()
2021-07-05 12:44:44 +00:00
m = re.match(r"\[\d+.*? \d+\] (.*?)\"", msg)
2021-06-30 14:41:07 +00:00
if m:
msg, = m.groups()
print(doc["time"], colored(doc.get("host", "-"), "blue"), "\t", "% 30s" % colored(container_name, "yellow"), msg)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())