打印用于登录 Python 的时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28330317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print timestamp for logging in Python
提问by romanzipp
I want to print the current timestamp, when an event succeeded or not in my python script. By only adding...
我想打印当前时间戳,当我的 python 脚本中的事件成功与否时。通过只添加...
datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
.... at the beginning of each line, te same date appears in every line
.... 在每一行的开头,每一行都出现相同的日期
[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!
(I added time.sleep(5)
in between)
(我time.sleep(5)
在中间加了)
My next idea was to create a function, calling the current time, but i'm failing at embedding this function to the print
command.
我的下一个想法是创建一个函数,调用当前时间,但我无法将此函数嵌入到print
命令中。
File rs.py
文件 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")
File myapp.py
文件 myapp.py
import rs # importing rs.py
print rs.OK + hostname + "is up!"
time.sleep(3)
print rs.ERR+ hostname + "is down!"
Is printing:
正在打印:
>>> [INFO] 04.Feb 2015 20:49:41: xxx is up!
>>> [ERR ] 04.Feb 2015 20:49:41: xxx is down!
采纳答案by gae123
Before the first time you log anything do this:
在您第一次记录任何内容之前,请执行以下操作:
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
Example on the REPL:
REPL 示例:
>>> import logging
>>> logging.basicConfig(
... format='%(asctime)s %(levelname)-8s %(message)s',
... level=logging.INFO,
... datefmt='%Y-%m-%d %H:%M:%S')
>>>
>>> logging.info('an info messge')
2017-05-25 00:58:28 INFO an info messge
>>> logging.debug('a debug messag is not shown')
>>>
回答by paidhima
Something like the below would do:
像下面这样的事情会做:
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
Have a look at the logging
module for Python. You don't need to mess about with creating your own date, just let the logging module do it for you. That formatter object can be applied to a logging handler so you can just log with logger.info('This is an info message.')
. No print statements required.
查看logging
Python 模块。您无需费心创建自己的日期,只需让日志记录模块为您完成即可。该格式化程序对象可以应用于日志处理程序,因此您只需使用logger.info('This is an info message.')
. 不需要打印语句。
Here's a boilerplate procedure I use:
这是我使用的样板程序:
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
回答by Gab
The datetime is calculated when the string is formed. So in your case, only once at the initialisation. Instead, you should do something like this:
日期时间是在字符串形成时计算的。所以在你的情况下,只有一次在初始化。相反,您应该执行以下操作:
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
To log, just do use ok()
which will reevaluate the datetime each time.
要记录,只需使用ok()
它每次都会重新评估日期时间。
Note that @paidhima suggestion is also good.
请注意,@paidhima 的建议也不错。