python基础-模块:logging

logging的基本配置

import logging

# 默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET)
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s %(name)s [line:%(lineno)d] %(levelname)s %(message)s",
                    datefmt = '%a, %d %b %Y %H:%M:%S',
                    filename = "hello.log",
                    filemode = "w")

logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
logging.critical("critical")

 

搞一个函数用于输出日志记录

import logging

logger = logging.getLogger()

def get_logger():
    # 创建一个handler,用于写入日志文件
    fh = logging.FileHandler('test.log')

    # 再创建一个handler,用于输出到控制台
    sh = logging.StreamHandler()

    #创建输出日志的格式
    f = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # 绑定格式
    fh.setFormatter(f)
    sh.setFormatter(f)

    logger.addHandler(fh)  # logger对象可以添加多个fh和ch对象
    logger.addHandler(sh)

    return get_logger

logobj=get_logger()


logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')





# 2017-04-27 10:04:25,035 - root - WARNING - logger warning message
# 2017-04-27 10:04:25,036 - root - ERROR - logger error message
# 2017-04-27 10:04:25,036 - root - CRITICAL - logger critical message
# 2017-04-27 10:09:11,207 - root - WARNING - logger warning message
# 2017-04-27 10:09:11,215 - root - ERROR - logger error message
# 2017-04-27 10:09:11,215 - root - CRITICAL - logger critical message
# 2017-04-27 10:10:11,291 - root - WARNING - logger warning message
# 2017-04-27 10:10:11,291 - root - ERROR - logger error message
# 2017-04-27 10:10:11,291 - root - CRITICAL - logger critical message

  

 

posted @ 2017-09-20 15:06  Adamanter  阅读(89)  评论(0编辑  收藏  举报