How do I format my output in the datetime module?

Viewed 34

So, I'm just messing around with the datetime and logging module in python3 and I'm trying to get timestamps from the datatime module to appear along with the logging event.

I want the output to look like: 7/16/20 22:18:20 DEBUG Test1 debug message

My problem: I can't get the data and time to appear to the left of my logging events.

from datetime import datetime

logging.basicConfig(level=logging.DEBUG,
                    datefmt='%m/%d/%Y %H:%M:%S',
                    filemode='a')


def set_logger(name):
    date_str = datetime.now().strftime("%Y_%m_%d")
    file_name = name + "_" + date_str
    if file_name:
        logger = logging.getLogger(name)
        logger.addHandler(logging.FileHandler(file_name))
        return logger


logger = set_logger("Test1")

logger.debug('Test1 debug message')
logger.info('Test1 info message')
logger.warning('Test1 warning message')
logger.error('Test1 error message')

logger = set_logger("Test2")

logger.debug('Test2 debug message')
logger.info('Test2 info message')
logger.warning('Test2 warning message')
logger.error('Test2 error message')


logger = set_logger("Test3")

logger.debug('Test3 debug message')
logger.info('Test3 info message')
logger.warning('Test3 warning message')
logger.error('Test3 error message')

Even with date_str being added to file_name it still won't print in my console. :/

1 Answers

Always read the documentation carefully, I know it can be tedious (especially with dates and times) but it will usually be a huge help in the future.

The basicConfig method from the logging module can take a format option. It is initialized as formatted string that looks like

FORMAT = '%(asctime)s: %(levelname)s: %(message)s'

Now that the format is initialized you can pass it into the format option inside the basicConfig as

logging.basicConfig(level=logging.DEBUG,
                    format=FORMAT, 
                    datefmt='%m/%d/%Y %H:%M:%S',
                    filemode='a')

That should give you the desired output of 07/16/2020 21:40:23: DEBUG: Test1 debug message... and so on

You also don't need that if statement in your set_logger function either


So your code should look like :

import logging
from datetime import datetime

FORMAT = '%(asctime)s: %(levelname)s: %(message)s'

logging.basicConfig(level=logging.DEBUG,
                    format=FORMAT,
                    datefmt='%m/%d/%Y %H:%M:%S',
                    filemode='a')


def set_logger(name):
    date_str = datetime.now().strftime("%Y_%m_%d")
    file_name = name + "_" + date_str
    logger = logging.getLogger(name)
    logger.addHandler(logging.FileHandler(file_name))
    return logger


logger = set_logger("Test1")

logger.debug('Test1 debug message')
logger.info('Test1 info message')
logger.warning('Test1 warning message')
logger.error('Test1 error message')

logger = set_logger("Test2")

logger.debug('Test2 debug message')
logger.info('Test2 info message')
logger.warning('Test2 warning message')
logger.error('Test2 error message')


logger = set_logger("Test3")

logger.debug('Test3 debug message')
logger.info('Test3 info message')
logger.warning('Test3 warning message')
logger.error('Test3 error message')

You can read the docs here: https://docs.python.org/3/library/logging.html#logging.Formatter https://docs.python.org/3/library/datetime.html

Related