How do i use different log levels in python?



  • If you are from a sysadmin background you will know that syslogd/rsyslogd has these types of log level messages

    DEBUG
    INFO
    WARNING
    ERROR
    CRITICAL

    Most of which are self-explanatory. There's a default log level set in the Python configuration.

    import logging
    
    logging.warning("This is a warning, only two cakes per person.")
    

    The output is:
    WARNING:root: This is a warning, only two cakes per person.

    What if we want to log output to a file instead?

    We import the logging module. Use the logging basicConfig function to set the filename and the log level, as we specified DEBUG, every log level is printed out.

    import logging
    
    logging.basicConfig(filename="output.log",level=logging.DEBUG)
    
    logging.info("Hello welcome to the cake competition")
    logging.warning("This is a warning, only two cakes per person.")
    

    The contents of the output.log file is:
    INFO:root: Hello welcome to the cake competition
    WARNING:root: This is a warning, only two cakes per person.


Log in to reply
 

© Lightnetics 2024