python logging 简单使用总结

logging模块简单使用:
----
1. logging.basicConfig简单设置 filename format datefmt level(默认为DEBUG)
 eg.
    logging.basicConfig(format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)s]: %(message)s', level=logging.DEBUG)


2. 如果要写入文件 上述参数中加入 filename='test.log'


3. 打印日志: logging.debug()  logging.info() logging.warning() ...


4. output log message both to file&&terminal


    * python2中logging 输出到file和stdout是互斥的。 需要用到logger=logging.getLogger() 对象,然后为其addHandler两个handler
        filename='./test.log'
        level=logging.DEBUG
        format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)s]: %(message)s'


        s = logging.StreamHandler() #new stdout Handler
        s.setLevel(level)
        s.setFormatter(logging.Formatter(format))


        logging.basicConfig(filename=filename, format=format, level=level) #set default Handle
        logging.getLogger().addHandler(s) #get the default(root) Logger and add stdout Handler


    * python3中很简单
        targets = logging.StreamHandler(sys.stdout), logging.FileHandler('test.log')
        logging.basicConfig(format='%(message)s', level=logging.INFO, handlers=targets)
展开阅读全文

没有更多推荐了,返回首页