格式化记录器以忽略ANSII代码Python日志记录

2024-09-30 05:15:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个python脚本,它使用parallel-ssh模块(又名pssh)在远程节点上运行各种命令。其中一个命令是puppet agent -t,它使用ANSII颜色代码输出。 当脚本正在运行并输出到终端时,颜色按预期工作。但是,在脚本日志中,我看到它并没有解析ANSII代码,而是为每一行提供了一个难看的包装器,如下所示:

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')方法修改logger配置,这是我在this thread中找到的,如下所示:

^{pr2}$

脚本运行正常,但是没有任何更改,日志中仍然有这些ANSII代码。 我假设可能还有另一个地方可以为pssh logger设置单独的处理程序,但我找不到它。在

任何帮助都将不胜感激!在


Tags: 代码in命令info脚本isagentcatalog
3条回答

此版本保留原始输出并添加'挪威标准'所以您既有原始输出,也有没有ANSI格式的输出

import re

client = pssh.ParallelSSHClient(nodes, pool_size=args.batch, timeout=10, num_retries=1)

output = client.run_command(command, sudo=True)

for node in output:
    # let's remove ansi formatting and put it into 'stdout.noansi'...
    output[node]['stdout.noansi'] = re.sub(r'\x1b\[[^m]*?m', '', output[node]['stdout'], re.I | re.S | re.M)
    print '       - <<<<< NOANSI OUTPUT >>>>>        -'
    [print '[{0}] {1}'.format(node, line) for line in output[node]['stdout.noansi'] ]
    print '       - <<<<< ORIGINAL OUTPUT >>>>>        -'
    [print '[{0}] {1}'.format(node, line) for line in output[node]['stdout'] ]

当前代码只转义实际的日志模板。希望有人能来告诉您如何正确地做到这一点,但是您可以使用日志适配器,它类似于日志记录器,只是它允许您修改正在记录的消息。在

class myAdapter(logging.LoggerAdapter):

    def process(self, msg, kwargs):
        msg = re.sub(r'\x1b[^m]*m', '', msg)
        return '%s' % (msg), kwargs

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 myAdapter(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)

更多信息可以在日志记录手册中找到:https://docs.python.org/2/howto/logging-cookbook.html

你试过禁用木偶颜色吗?在

puppet agent -t  color=false

相关问题 更多 >

    热门问题