Last active
October 23, 2020 10:24
-
-
Save Informatic/0427d26242092da6a65c71c4f384f0b3 to your computer and use it in GitHub Desktop.
python logging rotating gzipping handler
This file contains 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
# | |
# A quick tip on how to set up rotating logging handler with | |
# automatic gzipping of rotated files. Tested on python 3.7 | |
# | |
# | |
# Testing tip: | |
# python gziplogging.py | |
# touch example.log --date='2005/01/01' | |
# python gziplogging.py | |
# ls -lah *.log* | |
# | |
import gzip | |
import os | |
import shutil | |
import logging | |
import logging.handlers | |
logging.basicConfig(level=logging.INFO) | |
def gzip_namer(name): | |
return name + ".gz" | |
def gzip_rotator(src, dest): | |
if os.path.exists(src): | |
with open(src, "rb") as f_in: | |
with gzip.open(dest, "wb") as f_out: | |
shutil.copyfileobj(f_in, f_out) | |
os.remove(src) | |
common_formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s") | |
gzipping_handler = logging.handlers.TimedRotatingFileHandler( | |
"example.log", when="midnight" | |
) | |
gzipping_handler.namer = gzip_namer | |
gzipping_handler.rotator = gzip_rotator | |
gzipping_handler.setFormatter(common_formatter) | |
logging.getLogger().addHandler(gzipping_handler) | |
logging.info("hello world!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment