Python Logging To File And Stdout Code Example


Example 1: python logging to file

import logging import sys  logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s',                                '%m-%d-%Y %H:%M:%S')  stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(logging.DEBUG) stdout_handler.setFormatter(formatter)  file_handler = logging.FileHandler('logs.log') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter)  logger.addHandler(file_handler) logger.addHandler(stdout_handler)

Example 2: python logging to file

import logging  """ DEBUG INFO WARNING ERROR CRITICAL """ # asctime: time of the log was printed out # levelname: name of the log # datefmt: format the time of the log # give DEBUG log logging.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',     datefmt='%d-%m-%Y:%H:%M:%S',     level=logging.DEBUG,     filename='logs.txt')  logger = logging.getLogger('my_app')  logger.debug("This is a debug log") logger.info("This is an info log") logger.critical("This is critical") logger.error("An error occurred")

Example 3: python log to file and console

import logging  logging.basicConfig(     level=logging.INFO,     format="%(asctime)s [%(levelname)s] %(message)s",     handlers=[         logging.FileHandler("debug.log"),         logging.StreamHandler()     ] )

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable