cons基本日志

2024-04-25 03:53:00 发布

您现在位置: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")

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


Tags: getdatetimedatereturntimedef记录时间
2条回答

在每一个问题上,如果你在重新整理东西,那你就是做错了。你知道吗

对于你的问题,把它变成一个函数,一个沿着

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

或者对于更大的项目,使用logging模块。你知道吗

是的,使用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

如果要格式化datetime,请使用日志.格式化程序()

相关问题 更多 >