joshft91
joshft91

Reputation: 1885

Basic logging with console

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

Answers (2)

tom
tom

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

utdemir
utdemir

Reputation: 27216

On every problem; if you are repating stuff, you are doing it wrong.

For your question; just make it a function, something along the lines of;

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

Or for bigger projects, use logging module.

Upvotes: 5

Related Questions