1. 程式人生 > >Python中將打印輸出導向日誌文件

Python中將打印輸出導向日誌文件

.get mark lin groovy enter 好的 command 用法 lee

Python中將打印輸出導向日誌文件

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中將打印輸出導向日誌文件