Python Logging模块

python的Logging模块专门提供日志相关的功能,简要介绍,原文见Python Logging模块

Quick Start

导入模块后直接logging.waring()logging.error()简单粗暴地调用即可。默认的levelDEBUG,所以warning会打印出信息,info级别更低,不会输出信息。如果你不知道level等参数的意义请后面解释,淡定,继续往下看。

如果不特别配置,logging模块将日志打印到屏幕上(stdout)。

#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import logging
logging.warning('Watch out!')  # print message to console
logging.info('I told you so')  # will not print anything

Log写入文件

更常见的情形是把信息记录在log文件里。需要用logging.basicConfig()设置文件名以及level等参数,常见的level见下表。

LevelValueUsage
CRITICAL50严重错误,表明程序已不能继续运行了
ERROR40严重的问题,程序已不能执行一些功能了
WARNING30有意外,将来可能发生问题,但依然可用
INFO20证明事情按预期工作
DEBUG10详细信息,调试问题时会感兴趣。

如果设置levelINFO,那么DEBUG级别的信息就不会输出。常见的函数接口有debug(), info(), warning(), error() and critical(),分别对应log不同严重级别的信息。

注意把下面代码写入脚本(直接在terminal里不会生成文件),比如test_log.py

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG,filemode='w')
# filemode = 'w' 每次运行,重写log
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
cat example.log
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

改变Log输出格式

通过format参数,可以定制写入log文件的格式。

import logging
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

记录时间

通过datafmt参数,可以格式化输出log的时间。

import logging
logging.basicConfig(format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')

07/16/2016 12:10:35 AM is when this event was logged.

更丰富的Log控制

上面的代码大部分是利用默认配置,其实我们自定义更多。比如把输出到terminallog.txt文件里。

首先理解几个概念是有用的。

  • Logger 记录器,暴露了应用程序代码能直接使用的接口。
  • Handler 处理器,将(记录器产生的)日志记录发送至合适的目的地。
  • Filter 过滤器,提供了更好的粒度控制,它可以决定输出哪些日志记录。
  • Formatter 格式化器,指明了最终输出中日志记录的布局。

首先,创建一个logger,记录器,然后给其添加不同的handler,输出到不同的渠道,比如下面这个例子就会生成log.txt文件,并同时输出在terminal里。

import logging
# create logger with name
# if not specified, it will be root
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)

# create a handler, write to log.txt
# logging.FileHandler(self, filename, mode='a', encoding=None, delay=0)
# A handler class which writes formatted logging records to disk files.
fh = logging.FileHandler('log.txt')
fh.setLevel(logging.DEBUG)

# create another handler, for stdout in terminal
# A handler class which writes logging records to a stream
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)

# set formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)

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

# log it
logger.debug('Debug')
logger.info('Info')
2016-07-18 21:43:14,648 - my_logger - DEBUG - Debug
2016-07-18 21:43:14,650 - my_logger - INFO - Info

Ref:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
logging模块Python的内置模块,用于记录日志信息。它提供了一种灵活且可配置的方式,用于在应用程序中生成日志消息。通过使用logging模块,您可以根据不同的级别记录不同类型的消息,并且可以将这些消息输出到不同的目标,如控制台、文件或网络。 要使用logging模块,您需要先导入它: ```python import logging ``` 然后,您可以配置日志记录器并开始记录消息。以下是一个简单的示例,演示了如何使用logging模块记录日志消息: ```python import logging # 配置日志记录器 logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') # 记录不同级别的日志消息 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') ``` 在上面的示例中,我们首先使用`basicConfig()`方法配置了日志记录器。通过指定日志级别(例如`DEBUG`、`INFO`、`WARNING`、`ERROR`、`CRITICAL`),我们可以决定哪些级别的消息会被记录。我们还指定了日志文件的名称和格式。 然后,我们使用`debug()`、`info()`、`warning()`、`error()`和`critical()`方法来记录不同级别的日志消息。 您还可以在应用程序的其他位置使用相同的日志配置,并使用相同的记录器对象来记录消息。这样,您就可以在整个应用程序中保持一致的日志记录方式。 希望这个例子可以帮助您了解如何使用logging模块进行日志记录。如果您有任何进一步的问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值