Last active
October 8, 2020 15:21
-
-
Save etigui/0d0f0b6fb6fd33ae448409bcf590a264 to your computer and use it in GitHub Desktop.
Python - logger configuration to log to file and print to stdout
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
import sys | |
import logging | |
from logging import handlers | |
from logging.handlers import RotatingFileHandler | |
LOG_PYTH = '/var/log/logging.log' | |
LOG_LEVEL = logging.DEBUG | |
LOG_BACKUP_COUNT = 10 | |
LOG_MB = 1048576 | |
LOG_MAX_BYTES = MB * 10 | |
def init_logger(logger_name=None): | |
logger = None | |
try: | |
if | |
logger = logging.getLogger(logger_name) | |
logger.setLevel(LOG_LEVEL) | |
format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%d-%m-%Y %H:%M:%S') | |
# Write to stdout | |
ch = logging.StreamHandler(sys.stdout) | |
ch.setFormatter(format) | |
logger.addHandler(ch) | |
# Write to file | |
fh = handlers.RotatingFileHandler(LOG_PYTH, maxBytes=LOG_MAX_BYTES, backupCount=BACKUP_COUNT) | |
fh.setFormatter(format) | |
logger.addHandler(fh) | |
except Exception as ex: | |
sys.stderr.write(f'Could not init logger: {ex}') | |
sys.exit(1) | |
else: | |
return logger | |
def main(): | |
logger = init_logger() | |
logger.info('info') | |
logger.debug('debug') | |
logger.warning('warning') | |
logger.error('error') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment