除了更换_flush()
. 我通常发现在任何类中替换私有方法都是一种冒险的做法,更不用说第三方了。这是一个装饰 Fabric_flush()
方法并且还使用原生 Pythontime.asctime
方法来格式化时间戳的解决方案。
def time_decorator(msg):
"""
Decorates `msg` with current timestamp
Args:
msg(str): The log message from fabric
Returns:
str: Original message prepended with current date time
"""
if "\n" not in msg and msg.strip():
return "[%s] %s" % (time.asctime(), msg)
return msg
# Compose original method inside of decorator
_original_flush = OutputLooper._flush
OutputLooper._flush = lambda self, msg: {
_original_flush(self, time_decorator(msg))
}
@task
def uptime():
run('uptime')
测试一下,你的输出应该类似于:
> fab uptime -H 10.0.1.3,10.0.1.2
[10.0.1.3] Executing task 'uptime'
[10.0.1.3] run: uptime
[Thu Dec 15 19:34:35 2016] [10.0.1.3] out: 19:34:35 up 69 days, 4:22, 1 user, load average: 0.05, 0.03, 0.05
[Thu Dec 15 19:34:35 2016] [10.0.1.3] out:
[10.0.1.2] Executing task 'uptime'
[10.0.1.2] run: uptime
[Thu Dec 15 19:34:35 2016] [10.0.1.2] out: 19:34:35 up 70 days, 1:12, 1 user, load average: 0.00, 0.01, 0.05
[Thu Dec 15 19:34:35 2016] [10.0.1.2] out:
Done.
Disconnecting from ec2-user@10.0.1.3... done.
Disconnecting from ec2-user@10.0.1.2... done.