一、logging基本https://www.cnblogs.com/huaizhi/p/11245246.html
import logging
logging.basicConfig() ---默认项 只会打印在控制台,没有指定文件目录
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
=========== 默认配置项,只会打印warning级别以及以上级别
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message
添加参数后:
import logging logging.basicConfig(filename='log.text', filemode='w', format="%(asctime)s %(name)s %(levelname)s:%(message)s", datefmt='%d-%M-%Y %H:%M:%S', level=logging.INFO) --指定了文件后,就不会再控制台打印,会直接存到指定文件中 logging.debug('This is a debug message') logging.info('This is an info message') logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message') try: print(5 / 0) except Exception as e: logging.exception('occurred') --可以打印出具体的问题。
二、logger自定义(实现控制台和输入文件中):
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
try:
open("sklearn.txt", "rb")
except (SystemExit, KeyboardInterrupt):
raise
except Exception:
logger.error("Faild to open sklearn.txt from logger.error", exc_info=True)
logger.info("Finish")
三.实现一个py文件一个日志,且日志大于5M自动覆盖https://www.cnblogs.com/yfacesclub/p/9001073.html