Python(37):使用logging的配置文件配置日志

Python(37):使用logging的配置文件配置日志

输出日志到控制台和日志文件方法:

创建一个日志配置文件,然后使用fileConfig()函数来读取该文件的内容。

方法1:输出日志到文件,文件是固定的

方法2:输出日志到文件,定时生成新日志文件,推荐使用这个

一、fileConfig()函数说明

该函数实际上是对configparser模块的封装,关于configparser模块的介绍。

函数定义:

该函数定义在loging.config模块下:

logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)

参数:

  • fname:表示配置文件的文件名或文件对象
  • defaults:指定传给ConfigParser的默认值
  • disable_existing_loggers:这是一个布尔型值,默认值为True(为了向后兼容)表示禁用已经存在的logger,除非它们或者它们的祖先明确的出现在日志配置中;如果值为False则对已存在的loggers保持启动状态。

二、方法1、logging日志配置StreamHandler,FileHandler

一、StreamHandler
流handler——包含在logging模块中的三个handler之一。
能够将日志信息输出到sys.stdout, sys.stderr 或者类文件对象(更确切点,就是能够支持write()和flush()方法的对象)。

只有一个参数:
class logging.StreamHandler(stream=None)

日志信息会输出到指定的stream中,如果stream为空则默认输出到sys.stderr。

二、FileHandler

logging模块自带的三个handler之一。继承自StreamHandler。将日志信息输出到磁盘文件上。

构造参数:
class logging.FileHandler(filename, mode='a', encoding=None, delay=False)
模式默认为append,delay为true时,文件直到emit方法被执行才会打开。默认情况下,日志文件可以无限增大。

1、配置文件:logging.conf

[loggers]
#Configure logger information. Must include a logger named root,other:logging.getLogger("fileAndConsole")
keys=root,file,fileAndConsole

[handlers]
#Define declaration handlers information.
keys=fileHandler,consoleHandler

[formatters]
#Set log format
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

#qualname:name in the logger hierarchy,logging.getLogger("fileAndConsole")
[logger_file]
level=DEBUG
handlers=fileHandler
qualname=file
propagate=1

[logger_fileAndConsole] #Log output to console and file
level=DEBUG
handlers=fileHandler,consoleHandler
qualname=fileAndConsole
propagate=0


[handler_consoleHandler] #Log output to console
class=StreamHandler
args=(sys.stdout,)
level=DEBUG
formatter=simpleFormatter

[handler_fileHandler]     #Log output to file
class=FileHandler
args=('./log/test.log', 'a')
level=DEBUG
formatter=simpleFormatter

[formatter_simpleFormatter]
format=%(asctime)s - %(module)s - %(thread)d - %(levelname)s : %(message)s
datefmt=%Y-%m-%d %H:%M:%S

2、调用logtest.py

import logging.config

# '读取日志配置文件'
logging.config.fileConfig('./conf/logging.conf')

# 创建一个日志器logger
logger = logging.getLogger('fileAndConsole')
logger.debug('debug')
logger.info('info')
logger.warning('warn')
logger.error('error')
logger.critical('critical')

3、结果展示

控制台和test.log都产生日志

控制台

test.log

三、方法2、logging日志配置StreamHandler,TimedRotatingFileHandler

定时循环日志handler,位于logging.handlers,支持定时生成新日志文件。
class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
参数when决定了时间间隔的类型,参数interval决定了多少的时间间隔。如when=‘D’,interval=1,就是指一天的时间间隔,backupCount决定了能留几个日志文件。超过数量就会丢弃掉老的日志文件。

类型单位
‘S’
‘M’
‘H’
‘D’
‘W0’-‘W6’周一至周日
‘midnight’每天的凌晨

1、配置文件:logging.conf

#以下是和方法一不同的地方,使用TimedRotatingFileHandler
[handler_fileHandler]     #Log output to file
class=logging.handlers.TimedRotatingFileHandler
args=('./log/test.log','midnight')
level=DEBUG
formatter=simpleFormatter
[loggers]
#Configure logger information. Must include a logger named root,other:logging.getLogger("fileAndConsole")
keys=root,file,fileAndConsole

[handlers]
#Define declaration handlers information.
keys=fileHandler,consoleHandler

[formatters]
#Set log format
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

#qualname:name in the logger hierarchy,logging.getLogger("fileAndConsole")
[logger_file]
level=DEBUG
handlers=fileHandler
qualname=file
propagate=1

[logger_fileAndConsole] #Log output to console and file
level=DEBUG
handlers=fileHandler,consoleHandler
qualname=fileAndConsole
propagate=0


[handler_consoleHandler] #Log output to console
class=StreamHandler
args=(sys.stdout,)
level=DEBUG
formatter=simpleFormatter

[handler_fileHandler]     #Log output to file
class=logging.handlers.TimedRotatingFileHandler
args=('./log/test.log','midnight')
level=DEBUG
formatter=simpleFormatter

[formatter_simpleFormatter]
format=%(asctime)s - %(module)s - %(thread)d - %(levelname)s : %(message)s
datefmt=%Y-%m-%d %H:%M:%S

2、调用logtest.py

import logging.config

# '读取日志配置文件'
logging.config.fileConfig('./conf/logging.conf')

# 创建一个日志器logger
logger = logging.getLogger('fileAndConsole')
logger.debug('debug')
logger.info('info')
logger.warning('warn')
logger.error('error')
logger.critical('critical')

3、结果展示

控制台和test.log都产生日志

控制台

test.log

问题解决:

 问题:UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 44: illegal multibyte sequence

问题原因:l

logging.conf配置文件中注释有中文,并且编码格式为utf-8。

解决办法1:

Windows下的解决办法:把日志配置文件:logging.conf改成ANSI编码

Linux下的解决办法:把日志配置文件:logging.conf改成UTF-8编码

解决办法2:

logging.conf的注释全部修改为英文(编码格式为utf-8也没关系),这种方式更好些。

其他用代码配置的可参考

python的logging模块中的配置文件

python之logging的文件配置 - 简书 (jianshu.com)

python之配置日志的几种方式

python自动按日期保存日志文件

https://blog.csdn.net/yypsober/article/details/51800120

https://blog.csdn.net/Liu_Jilong/article/details/131896723

  • 22
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python中,可以使用logging模块来记录日志信息,方便程序员在开发和生产环境中进行调试和问题排查。logging模块提供了全局配置方法,可以通过配置来控制日志的格式、输出方式和级别等。 下面是一个简单的例子,展示如何使用logging模块进行全局配置: ``` import logging # 配置日志格式 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') # 创建一个StreamHandler,用于输出到控制台 console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) # 创建一个FileHandler,用于输出到文件 file_handler = logging.FileHandler('example.log') file_handler.setFormatter(formatter) # 创建一个Logger实例 logger = logging.getLogger('example') logger.setLevel(logging.DEBUG) # 将StreamHandler和FileHandler添加到Logger实例中 logger.addHandler(console_handler) logger.addHandler(file_handler) ``` 在上面的例子中,首先创建了一个Formatter对象,用于配置日志的格式。然后,创建了一个StreamHandler和FileHandler,分别用于将日志输出到控制台和文件中。接下来,创建了一个Logger实例,并设置了日志级别为DEBUG。最后,将StreamHandler和FileHandler添加到Logger实例中。 通过全局配置,可以方便地控制日志的输出方式和级别。在程序中,只需要使用logger对象来记录日志即可,例如: ``` logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message') ``` 通过上述配置日志信息将输出到控制台和文件中,并且可以根据需要调整日志级别。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宁宁可可

您的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值