Skip to content

Instantly share code, notes, and snippets.

@vubon
Created July 16, 2020 10:07
Show Gist options
  • Save vubon/b1048057e8d59fc4e0f07258c914c7d8 to your computer and use it in GitHub Desktop.
Save vubon/b1048057e8d59fc4e0f07258c914c7d8 to your computer and use it in GitHub Desktop.
Python logging example with Time Rotating File Handler
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