11

I am trying to use logging in my small python project. Following the tutorial, I added the code below to my code, but the message wan't logged to the file as it was supposed to.

import logging logging.basicConfig( filename = "a.log", filemode="w", level = logging.DEBUG) logging.error("Log initialization failed.") 

There was no log file created in the pwd. (I have used the following code to print out the pwd, and I am sure I checked the right directory.) So I manually created the file and ran the code, but the message was still not logged.

print "argv: %r"%(sys.argv,) print "dirname(argv[0]): %s"%os.path.abspath(os.path.expanduser(os.path.dirname(sys.argv[0]))) print "pwd: %s"%os.path.abspath(os.path.expanduser(os.path.curdir)) 

Has someone any clue what I did wrong here? Thanks in advance.

15
  • When you say There was log file, do you mean there was no log file? Commented Mar 1, 2013 at 21:44
  • 3
    Nope, your example works for me. What python version? Commented Mar 1, 2013 at 21:44
  • David: Yes, I meant there was no log file generated by the logging mechanism. (I am not sure if this is the supposed behavior though). Commented Mar 1, 2013 at 21:46
  • Martijn: I'm running: Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on Windows 7 (64 bit) Commented Mar 1, 2013 at 21:46
  • Are you sure the logging code actually happened (did you put it in a function, or something similar)? Did you try putting a print statement next to it? Commented Mar 1, 2013 at 21:48

1 Answer 1

26

You called basicConfig() twice at least; the first time without a filename. Clear the handlers and try again:

logging.getLogger('').handlers = [] logging.basicConfig( filename = "a.log", filemode="w", level = logging.DEBUG) 
Sign up to request clarification or add additional context in comments.

2 Comments

where are the other calls?
@andrew: I called logging.info before basicConfig, and I thought it was harmless, so I didn't include it in the code above. The [Python logging HowTo][1] has stated this clearly, but I missed it somehow: The call to basicConfig() should come before any calls to debug(), info() etc. As it’s intended as a one-off simple configuration facility, only the first call will actually do anything: subsequent calls are effectively no-ops. [1]: docs.python.org/2/howto/logging.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.