基本日志与控制台

时间:2013-10-18 19:20:28

标签: python

我正在搞乱python,我想跟踪一些事件发生的日期/时间。现在,输出到控制台就可以了。

目前,我正在处理它:

首先,将格式化的日期/时间包装在括号中:

def get_date_time():
  now = datetime.datetime.now().strftime("%Y/%m/%d %I:%M:%S")
  return "[" + now + "]"

接下来,只要我想“记录”某个动作,就这样调用它:

print(get_date_time(), "Outputting whatever text here")

这样做有什么不对吗?有没有更有效/干净的方法呢?可能没有,只是让我很好奇。

2 个答案:

答案 0 :(得分:5)

关于每一个问题;如果你正在复制的东西,你做错了。

对于你的问题;只是让它成为一种功能,类似的东西;

def log(s):
    print(get_date_time(), s)

或者对于较大的项目,请使用logging模块。

答案 1 :(得分:2)

是的,使用Python日志记录模块。 http://docs.python.org/2/library/logging.html

如果您愿意,可以将所有日志格式化为输出日期时间。

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='/tmp/myapp.log',
                    filemode='w')
logging.debug('A debug message')

打印

2004-07-02 13:00:08,743 DEBUG A debug message

如此处所见http://docs.python.org/2.4/lib/minimal-example.html

如果您希望格式化日期时间,请使用logging.formatter()