Last active
February 19, 2020 13:43
-
-
Save meatballhat/6a16aba3caf9b64a51a11c1a8dbf4460 to your computer and use it in GitHub Desktop.
python3-based rotating log sink
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import logging | |
import os | |
import sys | |
from logging.handlers import RotatingFileHandler | |
def main(sysargs=sys.argv[:], stdin=sys.stdin): | |
max_bytes = int(os.environ.get('MAX_BYTES', '10240')) | |
backup_count = int(os.environ.get('BACKUP_COUNT', '2')) | |
log = logging.getLogger(__name__) | |
log.setLevel(logging.DEBUG) | |
log.propogate = False | |
handler = RotatingFileHandler(sysargs[1], | |
mode='a+', | |
maxBytes=max_bytes, | |
backupCount=backup_count, | |
encoding='utf-8') | |
handler.setLevel(logging.DEBUG) | |
handler.setFormatter( | |
logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) | |
log.addHandler(handler) | |
try: | |
for line in stdin: | |
log.info(line.rstrip('\n')) | |
except KeyboardInterrupt: | |
return 0 | |
except Exception: | |
return 1 | |
finally: | |
handler.flush() | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment