python日志模块logging

python使用日志模块logging

在python项目中可以使用logging模块来管理记录的日志。

简单配置

使用basicConfig()方法简单地配置logger即可满足基本的需求。

basicConfig()方法参数如下:

参数名称参数说明
filename日志输出文件的文件名
filemode打开文件的模式,有r(+)、w(+)和a(+)
format日志输出的格式
datefat日志输出的日期格式
style格式占位符
level设置日志输出级别
stream定义输出流,不能与filename参数同时使用
handles定义处理器,用来创建handler对象,不能和filename、stream参数同时使用

示例代码如下:

import logging

logging.basicConfig(filename="test.log", filemode="w", format="%(asctime)s %(name)s:%(levelname)s:%(message)s", datefmt="%d-%M-%Y %H:%M:%S", level=logging.DEBUG)
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')

#使用logging输出日志
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')
自定义logger

除了使用basicConfig()方式配置logger之外,我们还可以自定义logger。示例代码:

import logging
import logging.handlers

def getLogger():
    logger = logging.getLogger("logger")

    handler1 = logging.StreamHandler()                                  #获取输出流handler,用于将日志输出到命令行
    handler2 = logging.FileHandler(filename="segmentation.log")         #获取文件handler,用于将日志输出到文件

    logger.setLevel(logging.DEBUG)                                      #设置日志等级
    handler1.setLevel(logging.DEBUG)
    handler2.setLevel(logging.DEBUG)

    formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")     #设置日志输出的格式
    handler1.setFormatter(formatter)
    handler2.setFormatter(formatter)

    logger.addHandler(handler1)                                         #日志输出到handler
    logger.addHandler(handler2)

    return logger
    
#使用logger输出日志
logger = getLogger()
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

其中,输出格式formatter变量如下:

变量格式描述
asctime%(sactime)s将日志时间构造成可读的形式
name%(name)日志对象的名称
filename%(filename)s不包含路径的文件名
pathname%(pathname)s包含路径的文件名
funcName%(funcName)s日志记录所在的函数名
levelname%(levelname)s日志级别名称
message%(message)s具体的日志信息
lineno%(lineno)d日志记录所在的行号
pathname%(pathname)s完整路径
process%(process)d当前进程ID
processName%(processName)s当前进程名称
thread%(thread)d当前线程ID
threadName%(threadName)s当前线程名称
Logger单例模式

一个系统只有一个Logger对象,并且该对象不能被直接实例化,这里使用的是单例模式,获取对象的方法为getLogger。

我们可以创建多个Logger对象,但是真正输出日志的是根Logger对象。每个Logger对象都可以设置一个名字,例如:

logger = logging.getLogger(__name__)    #__name__代表当前模块的名称(默认为__main__)

更多关于logging的内容,请查看官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值