Python Logging - Set Date as Filename
Perhaps you can use Python's TimedRotatingFileHandler
instead. You can set the interval to create a new log file every day with the date as the suffix.
Documentation--
- Python 2: https://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler
- Python 3: https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler
Note that the current day's log file won't have a date. This file handler only adds the date suffix when a new day starts.
Also, the suffix it uses is "%Y-%m-%d", which is a little different than what you want. But there's a SO question here about how you can alter that.
You can't use datetime
in a config file, as it doesn't know what it means. You can however add the Filehandler
in the python file itself:
import logging.config
from datetime import datetime
logging.config.fileConfig('aaa.conf')
logger = logging.getLogger('MainLogger')
fh = logging.FileHandler('{:%Y-%m-%d}.log'.format(datetime.now()))
formatter = logging.Formatter('%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.debug("TEST")
This way you can set the date as the file name in the handler.
This is the config file, note that you had a typo in the last formatter, you put fillname
instead of filename
and you forgot (
in message
.
[loggers]
keys=root,MainLogger
[handlers]
keys=consoleHandler
[formatters]
keys=consoleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_MainLogger]
level=DEBUG
handlers=consoleHandler
qualname=MainLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)
[formatter_consoleFormatter]
format=%(asctime)s | %(levelname)-8s | %(filename)s-%(funcName)s-%(lineno)04d | %(message)s
This Should work just fine.
This worked for me.
Update this,
args=(datetime.now().strftime('%Y_%m_%d.log'), 'a')
with this,
args=(\__import__("datetime").datetime.now().strftime('%Y_%m_%d.log'), 'a')
Reference (Example no 3): http://python-reference.readthedocs.io/en/latest/docs/functions/eval.html