I'm using Python 3.9 and Django 3.2. I have logging configured in my settings.py file
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
When I do logging in one of my classes, I do it like so
import logging
...
class TransactionService:
def __init__(self):
self._logger = logging.getLogger(__name__)
def my_method(self, arg1, arg2):
...
self._logger.info("Doing some logging here.")
How do I configure my logger such that when the message is printed out, it is prefixed by the current date and time?
This worked for me (adapted from thorndeux's answer):
import logging.config
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'prepend_date': {
'format': '{asctime} {levelname}: {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'prepend_date',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
logging.config.dictConfig(LOGGING)
logging.info('foo')
logging.warning('bar')
prints
2021-11-28 16:05:13,469 INFO: foo
2021-11-28 16:05:13,469 WARNING: bar