Created
July 16, 2020 10:07
-
-
Save vubon/b1048057e8d59fc4e0f07258c914c7d8 to your computer and use it in GitHub Desktop.
Python logging example with Time Rotating File Handler
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
import os | |
import logging | |
import logging.config | |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
LOGGER = { | |
'version': 1, | |
'disable_existing_loggers': False, | |
'formatters': { | |
'default': { | |
'format': '%(levelname)s | %(asctime)s | %(filename)s | %(module)s:%(funcName)s:%(lineno)d | %(message)s', | |
'datefmt': "%Y-%m-%d %H:%M:%S", | |
} | |
}, | |
'handlers': { | |
'info_file': { | |
'level': 'INFO', | |
'class': 'logging.handlers.TimedRotatingFileHandler', | |
'formatter': 'default', | |
'filename': BASE_DIR + "/logs/info.log", | |
'when': 'midnight', | |
'interval': 1, | |
'backupCount': 5 | |
}, | |
'exception_file': { | |
'level': 'ERROR', | |
'class': 'logging.handlers.TimedRotatingFileHandler', | |
'formatter': 'default', | |
'filename': BASE_DIR + "/logs/error.log", | |
'when': 'midnight', | |
'interval': 1, | |
'backupCount': 5 | |
}, | |
}, | |
'loggers': { | |
'info': { | |
'handlers': ['info_file'], | |
'level': 'INFO', | |
'propagate': True | |
}, | |
'exception': { | |
'handlers': ['exception_file'], | |
'level': 'ERROR', | |
'propagate': True | |
} | |
} | |
} | |
logging.config.dictConfig(LOGGER) | |
def main(): | |
logger = logging.getLogger(__name__) | |
error = logging.getLogger('exception') | |
logger.info('Started') | |
logger.info('Finished') | |
error.error('DEBUG') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment