Skip to content

Instantly share code, notes, and snippets.

@roderik333
Created February 2, 2023 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roderik333/a5666e38cbf3e66954b598ab96b0c086 to your computer and use it in GitHub Desktop.
Save roderik333/a5666e38cbf3e66954b598ab96b0c086 to your computer and use it in GitHub Desktop.
Windows log file watcher
"""Tailer"""
import time
import argparse
import sys
import os
def tail(filename: str, codes: list[int] = None, *, n: int = 1):
with open(filename, "r") as fp:
lines = fp.readlines()[-(n+1):-1]
for line in lines:
if codes is not None:
if int(line.split()[-2].strip()) in codes:
print(line, end="")
else:
print(line, end="")
print()
def follow(filename, codes: list[int] = None):
with open(filename, "r") as fp:
while True:
try:
where = fp.tell()
line = fp.readline()
if not line:
time.sleep(1)
fp.seek(where)
else:
if codes is not None:
if int(line.split()[-2].strip()) in codes:
print(line, end="")
else:
print(line, end="")
except KeyboardInterrupt:
sys.exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog="IIS log viewer",
description="View a IIS log and watch for changes",
)
parser.add_argument("-f", "--log-file", action="store", help="Full windows path to logfile")
parser.add_argument("-n", "--lines", action="store", default=1, type=int)
parser.add_argument("-c", "--codes", default=None, type=int, nargs="+")
parser.add_argument("-a", "--action", default="tail", const="tail", nargs="?",
choices=["tail", "follow"],
help="tail the file n-lines or follow the file interactively", )
args = parser.parse_args()
if not args.log_file:
parser.print_help()
sys.exit()
if args.action == "tail":
tail(args.log_file, codes=args.codes, n=int(args.lines))
elif args.action == "follow":
follow(args.log_file, codes=args.codes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment