logging

  1. after calling the logging.basicConfig() will set up logging, call logging.debug() to create a log message
  2. use logging.disable(logging.CRITCAL) to disable the logging messages, do not use print() ,it will be hard to remove when ou are done debugging.
  3. log to a file instead of the screen with the filename keyword argument to the basicConfig() function
logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s-%(levelname)s-%(message)s')

#add the filename = 'debug.txt' will redirect the logging to the file

logging.basicConfig(filename = 'debug.txt', level = logging.DEBUG, format = '%(asctime)s-%(levelname)s-%(message)s')

# the output will not show any logging messages, the logging will display in the file

log levels

  • debug(lowest) . logging.debug()
  • info
  • warning
  • error critical(highest)
import logging
logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s-%(levelname)s-%(message)s')
#logging.disable(logging.CRITICAL)
#if does not want to show so many debug messages , use disbale(logging.critical)
#will disable the logging which log level lower than critical

logging.debug('print the string need to show on screen')

Because no particular logger was specified, the system used the root logger. The debug and info messages didn't appear because by default, the root logger is configured to only handle messages with a severity of WARNING or above. The message format is also a configuration default, as is the output destination of the messages -sys.stderr. The severity level, the message format and destination can be easily changed, as shown in the example below:

logging.basicConfig(stream = sys.stdout,level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    )
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='/tmp/myapp.log',
                    filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')

ThebasicConfig()method is used to change the configuration defaults, which results in output (written to/tmp/myapp.log) which should look something like the following:

2004-07-02 13:00:08,743 DEBUG A debug message
2004-07-02 13:00:08,743 INFO Some information
2004-07-02 13:00:08,743 WARNING A shot across the bows

results matching ""

    No results matching ""