1

I am trying to add a timestamp to my Python logging code.

I have the code:

logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M')
log = logging.getLogger('Test_Service')

log.info('    Hello World')

But the output only shows:

INFO:Test_Service:    Hello World

How can I get the formatter to work here so that I can include the timestamp?

1
  • Did you do anything with the logging module before the code you show here? Commented Feb 20, 2014 at 22:56

1 Answer 1

1

Something else is calling basicConfig() first, and so your call has no effect.

You should ensure that:

  1. There is only one call to basicConfig() from your code, and that's in a main() or called from the if __name__ == '__main__ clause before a call to a main().

  2. There are no calls in your code to convenience logging module-level functions such as logging.debug() - such calls call basicConfig() automatically. Replace any such calls with logger.debug() where logger is any Logger instance (the root logger is allowed - just don't call the module-level convenience functions).

  3. If it still doesn't work, you are using third party code which calls basicConfig() (library code should never do this) and you will need to investigate further.

Sign up to request clarification or add additional context in comments.

1 Comment

Python 3.8 has a new parameter: force=True to override any existing basicConfig settings. Useful for Lambda function logging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.