Reputation: 1885
I'm messing around with python a bit, and I want to track the date/time of which some events happen. For now, outputting to the console will work just fine.
Currently, I'm handling it like so:
First, get the formatted date/time wrapped in brackets:
def get_date_time():
now = datetime.datetime.now().strftime("%Y/%m/%d %I:%M:%S")
return "[" + now + "]"
Next, whenever I want to "log" an action, call it like so:
print(get_date_time(), "Outputting whatever text here")
Is there anything wrong with doing it this way? Is there maybe a more efficient/clean way to do it? There may not be, it just has me curious.
Upvotes: 0
Views: 127
Reputation: 2365
Yes, use the Python logging module. http://docs.python.org/2/library/logging.html
You can format all your logs to output datetimes if you like.
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')
prints
2004-07-02 13:00:08,743 DEBUG A debug message
as seen here http://docs.python.org/2.4/lib/minimal-example.html
If you wish to formate the datetime, use logging.formatter()
Upvotes: 2