Python logging

本文详细介绍了Python中logging模块的基本使用方法,包括日志等级、配置格式、输出目标等内容,并展示了如何实现日志同时输出到文件和屏幕的效果。

python的logging主要有四个组件:
* logger: 日志类,应用程序往往通过调用它提供的api来记录日志;
* handler: 对日志信息处理,可以将日志发送(保存)到不同的目标域中;
* filter: 对日志信息进行过滤;
* formatter:日志的格式化;

logging是线程安全的。

控制台输出

默认情况下,logging将日志打印到屏幕,日志级别为WARNING。日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET。

# -*- coding: utf-8 -*-

import logging

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

输出

WARNING:root:This is warning message

通过logging.basicConfig函数对日志的输出格式及方式做相关配置

# -*- coding: utf-8 -*-
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='test.log',
                    filemode='w')

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

当前目录下test.log内容:

Tue, 07 Feb 2017 19:51:36 python-logging.py[line:10] DEBUG This is debug message
Tue, 07 Feb 2017 19:51:36 python-logging.py[line:11] INFO This is info message
Tue, 07 Feb 2017 19:51:36 python-logging.py[line:12] WARNING This is warning message

logging.basicConfig函数各参数:
- filename: 指定日志文件名
- filemode: 和file函数意义相同,指定日志文件的打开模式,’w’或’a’
- format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
- %(levelno)s: 打印日志级别的数值
- %(levelname)s: 打印日志级别名称
- %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
- %(filename)s: 打印当前执行程序名
- %(funcName)s: 打印日志的当前函数
- %(lineno)d: 打印日志的当前行号
- %(asctime)s: 打印日志的时间
- %(thread)d: 打印线程ID
- %(threadName)s: 打印线程名称
- %(process)d: 打印进程ID
- %(message)s: 打印日志信息
- datefmt: 指定时间格式,同time.strftime()
- level: 设置日志级别,默认为logging.WARNING
- stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

将日志同时输出到文件和屏幕

# -*- coding: utf-8 -*-
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='test.log',
                    filemode='w')

#################################################################################################
# 定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

当前目录下test.log内容:

Tue, 07 Feb 2017 19:56:23 python-logging.py[line:19] DEBUG This is debug message
Tue, 07 Feb 2017 19:56:23 python-logging.py[line:20] INFO This is info message
Tue, 07 Feb 2017 19:56:23 python-logging.py[line:21] WARNING This is warning message

控制台输出:

root        : INFO     This is info message
root        : WARNING  This is warning message

日志回滚

# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler

#################################################################################################
# 定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
r_handler = RotatingFileHandler('test.log', maxBytes=10*1024*1024, backupCount=5)
r_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
r_handler.setFormatter(formatter)
logging.getLogger('').addHandler(r_handler)

通过logging.config模块配置日志

#logger.conf
###############################################
[loggers]
keys=root,example01,example02

[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################
[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('test.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('test.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

将日志同时输出到文件和屏幕的例子:

# -*- coding: utf-8 -*-

import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

日志回滚的例子:

# -*- coding: utf-8 -*-

import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
Python 的 `logging` 模块是一个功能强大且灵活的日志记录工具,广泛用于调试、监控和记录应用程序运行状态。它的使用和配置可以分为基础用法和高级用法,包括通过代码直接配置和使用配置文件进行管理。 ### 基础用法 最简单的使用方式是导入 `logging` 模块,并使用默认的日志记录器。例如: ```python import logging logging.basicConfig(filename='app.log', level=logging.INFO) logging.info('This is an info message') ``` 上面的代码将日志级别设置为 `INFO`,并将日志信息写入 `app.log` 文件中。`basicConfig` 是一种快速配置方式,适用于简单的应用场景。 ### 高级配置 对于更复杂的项目,建议使用配置文件进行管理,以提高可维护性和灵活性。例如,可以使用 YAML 文件来定义日志格式、级别、处理器等。以下是一个示例配置文件 `logger.yml`: ```yaml version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: console: class: logging.StreamHandler formatter: simple level: DEBUG file: class: logging.FileHandler filename: 'app.log' formatter: simple level: INFO loggers: billingcodeowner: level: DEBUG handlers: [console, file] root: level: WARNING ``` 在代码中加载该配置文件: ```python import logging import logging.config import codecs import yaml with codecs.open("cfg/logger.yml", 'r', 'utf-8') as f: config = yaml.safe_load(f) logging.config.dictConfig(config) logger = logging.getLogger("billingcodeowner") logger.info("This is an info message") ``` ### 日志级别 `logging` 模块支持多种日志级别,从低到高依次为 `DEBUG`、`INFO`、`WARNING`、`ERROR` 和 `CRITICAL`。根据不同的需求,可以选择合适级别来记录信息。 ### 处理器和格式化器 - **处理器**(Handler):决定日志信息的输出位置,如控制台、文件、网络等。 - **格式化器**(Formatter):定义日志信息的格式。 例如,可以同时将日志输出到控制台和文件: ```python import logging logger = logging.getLogger('my_logger') logger.setLevel(logging.DEBUG) # 创建控制台处理器并设置级别 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # 创建文件处理器并设置级别 fh = logging.FileHandler('myapp.log') fh.setLevel(logging.INFO) # 创建格式化器 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) # 添加处理器到 logger logger.addHandler(ch) logger.addHandler(fh) logger.debug('Debug message') logger.info('Info message') logger.warning('Warning message') ``` ### 使用配置文件的优势 使用配置文件(如 YAML 或 JSON)可以将日志配置与代码分离,便于管理和修改。这种方式特别适合大型应用或分布式系统,因为它允许在不修改代码的情况下调整日志行为。 ### 日志模块的灵活性 Python 的 `logging` 模块不仅支持多种日志级别和处理器,还支持过滤器(Filter)和上下文信息(如 `extra` 参数),使得日志记录更加灵活和强大。 ### 常见问题 1. **如何避免重复的日志输出?** 确保每个 logger 只添加一次处理器,或者在配置文件中明确指定处理器。 2. **如何动态更改日志级别?** 可以通过代码动态更改 logger 或 handler 的级别,例如: ```python logger.setLevel(logging.DEBUG) ``` 3. **如何记录异常信息?** 使用 `logger.exception()` 方法可以记录异常信息,并自动附加堆栈跟踪: ```python try: # some code that may raise an exception except Exception as e: logger.exception("An error occurred: %s", e) ``` 4. **如何将日志发送到远程服务器?** 可以使用 `SocketHandler` 或第三方库(如 `logstash`)将日志发送到远程服务器。 5. **如何测试日志输出?** 可以使用 `unittest` 模块中的 `assertLogs` 方法来测试日志输出: ```python import logging import unittest class TestLogging(unittest.TestCase): def test_log_output(self): logger = logging.getLogger('test_logger') with self.assertLogs(logger, level='INFO') as cm: logger.info('Test message') self.assertEqual(cm.output, ['INFO:test_logger:Test message']) if __name__ == '__main__': unittest.main() ``` ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值