Python logging module console, file output

step

  • Importinglogging模块
  • Setting level(here DEBUG)
  • Add 文件handlerand流handler
import logging
logger=logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler=logging.FileHandler("log.txt")
handler.setLevel(logging.DEBUG)
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console=logging.StreamHandler()
console.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.addHandler(console)

use

info, debugAnd warningwrite, will console output operation, and written in the file. errorAnd it can be try...except...used together.

logger.info("Strt print log")
logger.debug("do sth")
logger.warning("sth failed")
try:
    1/0
except Exception:
    logger.error("Failed to do ...", exc_info=True)
logger.info('Finish')

Guess you like

Origin www.cnblogs.com/heenhui2016/p/11424154.html