我想在我的python脚本中成功或不成功时打印当前时间戳。 只添加......
datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
....在每一行的开头,每行显示相同的日期
[INFO] 04.Feb 2015 20:49:41: cl1
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
[INFO] 04.Feb 2015 20:49:41: cl2
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
[INFO] 04.Feb 2015 20:49:41: cl3
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
(我之间添加了time.sleep(5)
)
我的下一个想法是创建一个函数,调用当前时间,但我没有将此函数嵌入到print
命令中。
文件rs.py
OK = "[" + bc.OKGREEN + " OK " + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
INFO = "[" + bc.OKBLUE + "INFO" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
WARN = "[" + bc.WARN + "WARN" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
ERR = "[" + bc.ERR + "FAIL" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
DEB = "[" + bc.HEADER + "DEBUG" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
档案myapp.py
import rs # importing rs.py
print rs.OK + hostname + "is up!"
time.sleep(3)
print rs.ERR+ hostname + "is down!"
打印:
>>> [INFO] 04.Feb 2015 20:49:41: xxx is up!
>>> [ERR ] 04.Feb 2015 20:49:41: xxx is down!
答案 0 :(得分:57)
在您第一次登录之前,请执行以下操作:
adbd insecure
REPL上的示例:
boot.img
答案 1 :(得分:39)
如下所示:
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
查看Python的logging
模块。您不需要为创建自己的日期而烦恼,只需让日志记录模块为您完成。该formatter对象可以应用于日志记录处理程序,因此您只需使用logger.info('This is an info message.')
进行日志记录即可。无需打印声明。
这是我使用的样板程序:
import logging
def setup_custom_logger(name):
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
handler = logging.FileHandler('log.txt', mode='w')
handler.setFormatter(formatter)
screen_handler = logging.StreamHandler(stream=sys.stdout)
screen_handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.addHandler(screen_handler)
return logger
>>> logger = setup_custom_logger('myapp')
>>> logger.info('This is a message!')
2015-02-04 15:07:12 INFO This is a message!
>>> logger.error('Here is another')
2015-02-04 15:07:30 ERROR Here is another
答案 2 :(得分:0)
日期时间是在字符串形成时计算的。所以在你的情况下,只有一次初始化。相反,你应该做这样的事情:
def ok(hostname=None, status=None):
output = (
"[" + bc.OKGREEN + " OK " + bc.ENDC + "] " +
datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
)
if hostname is not None:
output += ' ' + hostname
if status is not None:
output += ' ' + status
print output
要记录,只需使用ok()
,每次都会重新评估日期时间。
请注意,@ paidhima的建议也很好。