我已經創建了一個python腳本,它使用parallel-ssh模塊(AKA pssh)爲了在遠程節點上運行各種命令。其中一個命令是puppet agent -t
,它使用ANSII顏色代碼輸出。 當腳本正在運行並輸出到終端時,着色按預期工作。然而,在腳本日誌我看到它不解析ANSII代碼,而是我得到一個醜陋的包裝的每一行,如下:格式記錄器忽略ANSII代碼 - Python日誌記錄
2016-01-12 20:23:30,748 INFO: [ubuntu01] ESC[1;31mWarning: Setting templatedir is deprecated. See http://links.puppetlabs.com/env-settings-deprecations
2016-01-12 20:23:30,748 INFO: [ubuntu01] (at /usr/lib/ruby/vendor_ruby/puppet/settings.rb:1139:in `issue_deprecation_warning')ESC[0m
2016-01-12 20:23:30,749 INFO: [ubuntu01] ESC[0;32mInfo: Retrieving pluginESC[0m
2016-01-12 20:23:31,984 INFO: [ubuntu01] ESC[0;32mInfo: Caching catalog for ubuntu01.puppetlabESC[0m
2016-01-12 20:23:32,014 INFO: [ubuntu01] ESC[0;32mInfo: Applying configuration version '1452623010'ESC[0m
2016-01-12 20:23:32,083 INFO: [ubuntu01] ESC[mNotice: Finished catalog run in 0.08 secondsESC[0m
2016-01-12 20:23:32,351 INFO: [ubuntu01] * agent is running
2016-01-12 20:23:32,353 INFO: [centos01] ESC[0;32mInfo: Retrieving pluginfactsESC[0m
2016-01-12 20:23:32,353 INFO: [centos01] ESC[0;32mInfo: Retrieving pluginESC[0m
2016-01-12 20:23:33,712 INFO: [centos01] ESC[0;32mInfo: Caching catalog for centos01.puppetlabESC[0m
2016-01-12 20:23:33,838 INFO: [centos01] ESC[0;32mInfo: Applying configuration version '1452623010'ESC[0m
2016-01-12 20:23:34,101 INFO: [centos01] ESC[mNotice: Finished catalog run in 0.27 secondsESC[0m
2016-01-12 20:23:34,421 INFO: [centos01] puppet (pid 2069) is running...
這是非常令人沮喪,因爲它使日誌的可讀性。 我試圖修改與re.compile(r'\x1b[^m]*m')
方法記錄器的配置,我在this thread發現,像這樣:
import logging
import re
ansi_escape = re.compile(r'\x1b[^m]*m')
message = ansi_escape.sub('', '%(message)s')
def set_logger(log_file):
"""Define the logger.."""
try:
logging.basicConfig(filename=log_file, level=logging.INFO,
format='%(asctime)s %(levelname)s: ' + message)
logger = logging.getLogger(__name__)
return logger
except IOError:
print "ERROR: No permissions to access the log file! Please run the script as root user (sudo will also do the trick)..\n"
exit(2)
腳本運行正常,然而,沒有變化和日誌仍然看起來雜亂無章所有這些ANSII碼。 我假設可能有另一個地方可以爲pssh記錄器設置單獨的處理程序,但我無法找到它。
任何幫助將非常感謝!
您當前的代碼取代了日誌模板,而不是實際的消息。解決這個問題最簡單的方法是清理記錄之前記錄的消息。 – Thtu
你能否提供一些細節? pssh模塊有它自己的記錄器AFAIK,所以我不確定在記錄之前我能夠處理輸出。 謝謝! –