Python 之logging

参考视频:https://www.youtube.com/watch?v=dvtjV4Xmtj0

1.简单用法,不能同时输出到屏幕加文件。 可以用logging.basicConfig()配置。

# Demo https://rgb-24bit.github.io/blog/2018/python-logging.html
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged')

2.1 若要同时输出到屏幕加文件。需要用handler 处理

Python 之logging

 

import os
import logging

logger = logging.getLogger() # create instance 对象实例

fh = logging.FileHandler('logging_test.log')
ch = logging.StreamHandler()


fm=logging.Formatter("%(asctime)s %(message)s")

fh.setFormatter(fm)
ch.setFormatter(fm)

logger.addHandler(fh)
logger.addHandler(ch)

logger.setLevel("DEBUG")  # 默认为warning, 打印3行

 

logger =logger()
logger.debug('debug')
logger.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")

2.2. 基本用法如2.1.

一般可以封装为一个函数,返回logger ,直接调用。

import os
import logging

'''
# Demo https://rgb-24bit.github.io/blog/2018/python-logging.html
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged')
'''

def logger():
    
    logger = logging.getLogger() # create  instance

    fh = logging.FileHandler('logging_test.log')
    ch = logging.StreamHandler()


    fm=logging.Formatter("%(asctime)s %(message)s")

    fh.setFormatter(fm)
    ch.setFormatter(fm)

    logger.addHandler(fh)
    logger.addHandler(ch)

    logger.setLevel("DEBUG")

    return logger

logger =logger()
logger.debug('debug')
logger.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")

 

3. Log 是树形关系,子log. 避免才坑,参考视频:

 

参考视频:https://www.youtube.com/watch?v=dvtjV4Xmtj0  

 

上一篇:豆瓣FM产品分析 | 纯粹极简的听歌APP


下一篇:《村口FM》第13期上线 关注红米荣耀旗舰之争 展望WWDC