Python---logging日志模块基本用法

Python—logging日志模块基本用法

日志一共分成5个等级,从低到高分别是:
DEBUG、INFO、WARNING、ERROR、CRITICAL
默认的是 WARNING,当在WARNING或之上时才被跟踪

控制台输出

import logging

# 通过logging.basicConfig函数对日志的输出格式及方式做相关配置
logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(name)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",  # 日期格式
    level=logging.INFO  # 最低显示等级
)
logging.info('this is a loggging info message')
logging.debug('this is a loggging debug message')
logging.warning('this is loggging a warning message')
logging.error('this is an loggging error message')
logging.critical('this is a loggging critical message')

输出至文件

import logging

logging.basicConfig(
    filename="./log.txt",
    filemode="a+",
    format="%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(name)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    level=logging.INFO
)
logging.info('this is a loggging info message')
logging.debug('this is a loggging debug message')
logging.warning('this is loggging a warning message')
logging.error('this is an loggging error message')
logging.critical('this is a loggging critical message')

既要把日志输出到控制台,也要写入日志文件

import logging

# create a logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)    # Log等级开关

# create a handler for write to log file
logfile = './log.txt'
fh = logging.FileHandler(logfile, mode='a+')
fh.setLevel(logging.DEBUG)      # 输出到file的log等级开关

# create a handler for output to console
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)    # 输出到console的log等级开关

# define the format of handler's output
formatter = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(name)s - %(message)s",
                              datefmt="%Y-%m-%d %H:%M:%S")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# add logger to handler
logger.addHandler(fh)
logger.addHandler(ch)

# 日志
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值