a. 利用sys.stdout将print行导向到你定义的日志文件中,例如:

import sys

# make a copy of original stdout route
stdout_backup = sys.stdout
# define the log file that receives your log info
log_file = open("message.log", "w")
# redirect print output to log file
sys.stdout = log_file print "Now all print info will be written to message.log"
# any command line that you will execute
... log_file.close()
# restore the output to initial pattern
sys.stdout = stdout_backup print "Now this will be presented on screen"

b. 利用logging模块(规范化日志输出,推荐!!)

由于logging模块的功能比较多,下面就放一些文档里介绍的简单的例子,更详细具体的用法请戳这里

需求 最好的实现方式
故障调查或者状态监测 logging.info()或logging.debug()(后者常用于针对性检测诊断的目的)
特定运行事件发出警告 logging.warning()
报告错误抑制不出发异常(常见于长时间运行的服务器进程的错误处理程序) logging.error(), logging.exception()或者logging.critical()

而以下是根据事件的严重性程度而应采取的logging函数的建议:

程度 使用场景
DEBUG 获得诊断问题是具体的信息
INFO 确认程序是否按正常工作
WARNING 在程序还正常运行时获取发生的意外的信息,这可能会在之后引发异常(例如磁盘空间不足)
ERROR 获取程序某些功能无法正常调用这类严重异常的信息
CRITICAL 获取程序无法继续运行的这类最严重异常信息

默认的等级是WARNING,也就是说logging函数在没有特别配置的前提下只追踪比WARNING程度更严重的异常。

下面就用一些例子来具体说明如何用logging函数记录日志信息:

# this is a simple example
import logging
# define the log file, file mode and logging level
logging.basicConfig(filename='example.log', filemode="w", level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

查看example.log文件可以看到以下信息:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

从多个文件记录日志

# myapp.py
import logging
import mylib def main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
mylib.do_something()
logging.info('Finished') if __name__ == '__main__':
main()
# mylib.py
import logging def do_something():
logging.info('Doing something')

输出的信息为

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished

改变默认输出信息的格式

import logging
# output format: output time - logging level - log messages
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logging.warning('This message will appear in python console.')

在python console中直接打印以下输出:

2016-8-2 2:59:11, 510 - WARNING - This message will appear in python console

logging高级用法

可以通过构建logger或者读取logging config文件对logging函数进行任意配置。

  • 构建logger法
import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG) # create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG) # create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch
ch.setFormatter(formatter) # add ch to logger
logger.addHandler(ch) # 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

以上程序结果会输出到python console中:

$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
  • 读取配置文件法
import logging
import logging.config logging.config.fileConfig('logging.conf') # create logger
logger = logging.getLogger('simpleExample') # 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

其中logging.conf文件格式为:(其实就是将前一种方法的各项配置参数写到logging.conf文件中)

[loggers]
keys=root,simpleExample [handlers]
keys=consoleHandler [formatters]
keys=simpleFormatter [logger_root]
level=DEBUG
handlers=consoleHandler [logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0 [handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,) [formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt= '%m/%d/%Y %I:%M:%S %p'

与前面一样,上述文件输出结果为:

$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

参考:stackoverflow: redirect prints to log file

Python中将打印输出导向日志文件的更多相关文章

  1. 使用python脚本实现统计日志文件中的ip访问次数

    使用python脚本实现统计日志文件中的ip访问次数,注意此脚本只适用ip在每行开头的日志文件,需要的朋友可以参考下 适用的日志格式: 106.45.185.214 - - [06/Aug/2014: ...

  2. Python中将打印输出日志文件

    一. 利用sys.stdout将print行导向到你定义的日志文件中,例如: import sys # make a copy of original stdout route stdout_back ...

  3. 使用python递归子目录处理日志文件

    重要说明: (1)python使用4个空格进行层次缩进的(不是tab),在eclipse里面可以直接使用tab缩进,是因为eclipse会实时地将tab转成4个空格 (2)在eclipse中安装pyD ...

  4. docker容器中日志文件过大处理方法

    背景 :在日常工作中一个基于centos镜像构建起来的python爬虫程序,日志文件在两个月内到了500G,日志存放在根目录下面,在不扩容的情况下把这个问题给解决掉.通过定时任务和脚本的方法,定期的清 ...

  5. 【Python语言】--Crontab结合Python脚本实现将日志每天写入到文件中

    一.前述 实际工作中将Python脚本每天定时写入到日志文件中的使用场景还是蛮多的,有很多种方法可以实现这种效果.本文选择一种方式实现,特将实现细节做如下分享,不当之处烦请指正. 二.具体 1.pyt ...

  6. python 实时遍历日志文件

    首先尝试使用 python open 遍历一个大日志文件, 使用 readlines() 还是 readline() ? 总体上 readlines() 不慢于python 一次次调用 readlin ...

  7. Python同时向控制台和文件输出日志logging的方法 Python logging模块详解

    Python同时向控制台和文件输出日志logging的方法http://www.jb51.net/article/66756.htm 1 #-*- coding:utf-8 -*- 2 import ...

  8. Linux(9)后台运行python程序并输出到日志文件

    后台运行python程序并标准输出到文件 现在有test.py程序要后台部署, 里面有输出内容 使用命令: nohup python -u test.py > test.log 2>&am ...

  9. python 接口测试1 --如何创建和打印日志文件

    python自带的logging实在是不好用,推荐使用logbook 思路如下: 1.创建path.py文件,获取工程根路径 2.创建log.py文件,在工程根路径下创建日志文件(文件名称按日期命名) ...

随机推荐

  1. Myeclipse10中出现Cannot return from outside a function or method错误提示

    最近发现myeclipse10中有几处bug 比如: Cannot return from outside a function or method onClick="return chec ...

  2. org.springframework.orm.hibernate3.support.OpenSessionInViewFilter作用

    在Spring与Hibernate集成时在web.xml要加入这样的过滤器: <filter> <filter-name>openSessionInView</filte ...

  3. 树莓派 2 win 10 IOT

    Setting up Windows 10 for IoT on your Raspberry Pi This week at the BUILD conference in San Francisc ...

  4. 微信 JSSDK .NET版

    /*因为官方 微信 JSSDK 只有PHP java版本的 我自己照着PHP的翻译过来的,可供参考.欢迎指正*/ [csharp] view plaincopy在CODE上查看代码片派生到我的代码片 ...

  5. C# 如何通过拼接XML调用存储过程来优化系统性能

    平常新增多条记录,需要多次访问数据库,这样会影响性能:如果把新增的数据拼接成XML形式,作为参数传给存储过程来处理,这只访问数据库一次,执行速度会快很多. 1.C#代码如下:XML拼接的字段不能出现& ...

  6. mybatis 中的稍微复杂些的sql语句

    mybatis 中的稍微复杂些的sql语句: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYP ...

  7. TCP长连接与短连接

    1.概念区别 所谓TCP短连接,是指通信双方有数据交互时,就建立一个TCP连接,数据发送完成后,则断开此TCP连接.也就是说TCP连接维持的时间比较短.一般银行网页数据交互都使用短连接.再比如说htt ...

  8. Eclipse的中文字体设置

    打开eclipse中文字体很小,简直难以辨认.在网上搜索发现这是由于Eclipse 用的字体是 Consolas,显示中文的时候默认太小了.解决方式有两种:一.把字体设置为Courier New  操 ...

  9. 【jmeter】属性和变量

    一.Jmeter中的属性: 1.JMeter属性统一定义在jmeter.properties文件中,我们可以在该文件中添加自定义的属性 2.JMeter属性在测试脚本的任何地方都是可见的(全局),通常 ...

  10. 【mybatis】之批量添加

    mybatis批量添加xml <insert id="batchCreate"> INSERT INTO `roomer` (`order`,name,idCard,m ...