[英]Python: Log to multiple log files
目前,我已將所有內容都記錄到一個日志文件中,但我想將其分離到多個日志文件中。 我查看了python文檔中的日志記錄,但他們沒有對此進行討論。
log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(filename=(os.path.join(OUT_DIR, + '-user.log')),
format=log_format, level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
目前,這是我進行日志記錄的方式。 我要執行的操作具有不同類型的錯誤或信息,請將該日志記錄到不同的日志文件中。 目前,當我執行logging.info('Logging IN')
和logging.error('unable to login')
將轉到相同的日志文件。 我想分開他們。 我需要創建另一個日志記錄對象來支持登錄到另一個文件嗎?
您可能/可能要做的事情(我沒有對logging
模塊進行過多研究,因此可能會有更好的方法來執行此操作)可能是使用流而不是文件對象:
In [1]: class LogHandler(object):
...: def write(self, msg):
...: print 'a :%s' % msg
...: print 'b :%s' % msg
...:
In [3]: import logging
In [4]: logging.basicConfig(stream=LogHandler())
In [5]: logging.critical('foo')
a :CRITICAL:root:foo
b :CRITICAL:root:foo
In [6]: logging.warn('bar')
a :WARNING:root:bar
b :WARNING:root:bar
進行進一步處理 :
假設您的日志文件已經存在,則可以執行以下操作:
import logging
class LogHandler(object):
format = '%(levelname)s %(message)s'
files = {
'ERROR': 'error.log',
'CRITICAL': 'error.log',
'WARN': 'warn.log',
}
def write(self, msg):
type_ = msg[:msg.index(' ')]
with open(self.files.get(type_, 'log.log'), 'r+') as f:
f.write(msg)
logging.basicConfig(format=LogHandler.format, stream=LogHandler())
logging.critical('foo')
這將允許您根據日志消息中的條件將日志分為多個文件。 如果找不到您要查找的內容,則默認為log.log
。
我從docs.python.org/2/howto/logging-cookbook.html創建了此解決方案
只需創建兩個日志文件處理程序,分配它們的日志記錄級別並將它們添加到您的記錄器中即可。
import os
import logging
current_path = os.path.dirname(os.path.realpath(__file__))
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
#to log debug messages
debug_log = logging.FileHandler(os.path.join(current_path, 'debug.log'))
debug_log.setLevel(logging.DEBUG)
#to log errors messages
error_log = logging.FileHandler(os.path.join(current_path, 'error.log'))
error_log.setLevel(logging.ERROR)
logger.addHandler(debug_log)
logger.addHandler(error_log)
logger.debug('This message should go in the debug log')
logger.info('and so should this message')
logger.warning('and this message')
logger.error('This message should go in both the debug log and the error log')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.