Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging not saving to file

Tags:

python

logging

I have been stuck on this for the past hour. I had plugged logging into my tkinter gui, but could not get it to work. I then started removing parts until I got at the bare bones example in the very python docs and it will not work. At this point I have nothing else to remove.

The code is as follows:

import logging

LOG_FILENAME = r'logging_example.out'


logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

f = open(LOG_FILENAME, 'rt')
try:
    body = f.read()
finally:
    f.close()

print('FILE:')
print (body)

The warning is printed to stdout, but the file is not generated. I am runing python 3.4, x64 on a windows 7. It is a anacondas distribution, so this is running in Ipython inside spyder.

I guess this should be working

like image 855
mvbentes Avatar asked Jul 01 '15 19:07

mvbentes


People also ask

How do I view logging information in Python?

Python Logging – INFO Level To log an INFO line using Python Logging, Check if the logger has atleast a logging level of INFO. Use logging.info() method, with the message passed as argument, to print the INFO line to the console or log file.


1 Answers

As Jonas Byström noted, this does work outside Ipython. It seems that Ipython configures a logging handler before I get the chance to do so. Also, basicConfig will do nothing if a handler is already present. So, in order to have it working in Ipython, one must do one of three things: 1) Add a new handler, OR 2)reload logging, OR 3) remove existing handlers. I did number 2 bellow.

import logging
from imp import reload
reload(logging)
LOG_FILENAME = r'logging_example.out'


logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

f = open(LOG_FILENAME, 'rt')
try:
    body = f.read()
finally:
    f.close()

print('FILE:')
print (body)

See theese for more information: Logging in ipython; More on the same

like image 137
mvbentes Avatar answered Sep 18 '22 15:09

mvbentes