问题
I use the Python logging framework with default settings. For some data compare reason:I have to compare the log with other data output. But the python log begin with a default, something like:
INFO:root:post params in transmitter
Can I set the python log output without INFO:root:
, like:
post params in transmitter
with my own log only?
Thx a lot!
回答1:
Sure thing. You could set the format to watever you like:
format: '%(message)s'
Like this:
logging.basicConfig(format='%(message)s', ...)
See the doc for more info: http://docs.python.org/library/logging.config.html
回答2:
Those "INFO:..." or "DEBUG:..." appear there because some handler defines that. My guess: the default handler is still there.
You can check it by taking a peek at logger.handlers right after you created it.
logger = logging.getLogger()
logger.handlers = [] # This is the key thing for the question!
# Start defining and assigning your handlers here
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
Also, you could just override the format for that default handler:
if (len(logger.handlers) > 0): # Check here whatever. Or try/except. You get the idea...
formatter = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s")
logger.handlers[0].setFormatter(formatter)
I am not a Python expert so maybe there is a better way to remove or even not create that default handler but this works pretty well for me.
Note: As stated in the docs, the .basicConfig is useful for simple loggers. If you have multiple streams, with multiple formats, it does not work as far as I know and you need to go with the custom handlers.
回答3:
endDate = '2015-07-24'
logging.basicConfig(filename="win" + strftime("%Y%m%d", localtime()) + ".txt", level=logging.DEBUG,format='%(message)s')
回答4:
Use a Formatter.
回答5:
Your really dont need to get into removing INFO word.. . (it shall really help you when your code would more messy and you would be using more stuff than just info like debugging exception etc)
If you want to compare you data with that data you can do something like skipping first 10 character (INFO:ROOT:) and then do whatever you feel like. Umm something like this:
f = open("my.log","a+")
lines = f.readlines()
for line in lines:
if(line[10:] == my_output):
do_whatever_you_feel_like()
来源:https://stackoverflow.com/questions/8353594/can-python-log-output-without-inforoot