How do i print out the date into a log file?



  • The format argument is used in the logging.basicConfig function called, %asctime, this on its own will print the date, however, if you want the date and time in a specific format too, you can use the datefmt argument.

    import logging
    
    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.DEBUG)
    
    logging.info("Hello welcome to the cake competition")
    logging.warning("This is a warning, only two cakes per person.")
    

    The output is:
    2018-06-18 11:03:02,087 INFO: Hello welcome to the cake competition
    2018-06-18 11:03:02,087 WARNING: This is a warning, only two cakes per person.

    With the datefmt

    import logging
    
    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', datefmt='%d/%m/%y', level=logging.DEBUG)
    
    logging.info("Hello welcome to the cake competition")
    logging.warning("This is a warning, only two cakes per person.")
    

    The output is:
    18/06/18 INFO: Hello welcome to the cake competition
    18/06/18 WARNING: This is a warning, only two cakes per person.


Log in to reply
 

© Lightnetics 2024