Print timestamp for logging in Python

I want to print the current timestamp, when an event succeeded or not in my python script. By only adding...

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)

My next idea was to create a function, calling the current time, but i'm failing at embedding this function to the printcommand.

File 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

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!
138307 次浏览

Something like below would do:

formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')

查看 Python 的 logging模块。您不需要为创建自己的日期而烦恼,只需让日志模块为您完成这项工作。可以将该格式化程序对象应用到日志处理程序,这样您就可以使用 logger.info('This is an info message.')进行日志记录。不需要打印声明。

下面是我使用的一个样板程序:

import logging
import sys


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

在字符串形成时计算日期时间。所以在你的情况下,只有一次在初始化。相反,你应该这样做:

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(),它将每次重新计算日期时间。

Note that @paidhima suggestion is also good.

在你第一次记录任何东西之前这样做:

logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')

Example on the 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')
>>>