Skip to content

Instantly share code, notes, and snippets.

@gongzhitaao
Last active May 1, 2024 18:08
Show Gist options
  • Save gongzhitaao/0072e4df3533d282b5b3928447df7195 to your computer and use it in GitHub Desktop.
Save gongzhitaao/0072e4df3533d282b5b3928447df7195 to your computer and use it in GitHub Desktop.
Python logging template
import logging
import logging.config
from datetime import datetime
import os
import sys
LOGFILE = '/tmp/{0}.{1}.log'.format(
os.path.basename(__file__),
datetime.now().strftime('%Y%m%dT%H%M%S'))
DEFAULT_LOGGING = {
'version': 1,
'formatters': {
'standard': {
'format': '%(asctime)s %(levelname)s: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
},
'simple': {
'format': '%(message)s',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
'level': 'DEBUG',
'stream': sys.stdout,
},
'file': {
'class': 'logging.FileHandler',
'formatter': 'simple',
'level': 'INFO',
'filename': LOGFILE,
'mode': 'w',
},
},
'loggers': {
__name__: {
'level': 'DEBUG',
'handlers': ['console', 'file'],
'propagate': False,
},
}
}
logging.basicConfig(level=logging.ERROR)
logging.config.dictConfig(DEFAULT_LOGGING)
log = logging.getLogger(__name__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment