python logging does not work at all

2019-04-05 14:46发布

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.

1条回答
姐就是有狂的资本
2楼-- · 2019-04-05 15:19

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)
查看更多
登录 后发表回答