Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

python - Changing logging's 'basicConfig' which is already set

I am using the logging module in python as:

import logging, sys
logger= logging.getLogger(__file__)
logging.basicConfig(stream = sys.stderr, level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')
logger.debug("Hello World")

Now, after I have set the basic configuration on line 3, I want to have a command line argument that can change the output stream from sys.stderr to a file.

I have read the doc and it says that if both filename and stream are present at the same time, the stream is ignored.

Now, I wanna know how do change the stream to a file after I have already done the basicConfig thing in line 3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you look in the Python sources for logging/__init__.py, you'll see that basicConfig() sets the handlers on the root logger object by calling addHandler(). If you want to start from scratch, you could remove all existing handlers and then call basicConfig() again.

# Example to remove all root logger handlers and reconfigure. (UNTESTED)
import logging

# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

# Reconfigure logging again, this time with a file.
logging.basicConfig(filename = 'myfile.log', level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...