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都产生日志

控制台

Python(37):使用logging的配置文件配置日志_第1张图片

test.log

Python(37):使用logging的配置文件配置日志_第2张图片

三、方法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都产生日志

控制台

Python(37):使用logging的配置文件配置日志_第3张图片

test.log

Python(37):使用logging的配置文件配置日志_第4张图片

问题解决:

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

Python(37):使用logging的配置文件配置日志_第5张图片

问题原因:l

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

解决办法1:

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

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

Python(37):使用logging的配置文件配置日志_第6张图片

解决办法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

你可能感兴趣的:(python相关,python,自动化)