Reputation: 4911
I haven't been able to find a solution to this problem elsewhere, even though it seems it should be a common one.
import logging
logging.basicConfig(filename='logs.log', level=logging.INFO)
logging.info('something happened')
I want to create and write to the log file, but instead it displays the messages in the notebook output cell.
Upvotes: 6
Views: 15792
Reputation: 1314
If you are encountering this issue in Jupyter Lab, it might also be because of this problem. Jupyter Lab doesn't seem to show the updated versions of log files that are opened even though they are updated. That's why I recommend using another application for specifically viewing log files like Visual Studio Code.
Upvotes: 0
Reputation: 21
log both file and jupyter
fh = logging.FileHandler('example.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
logging.info('Hello world')
Upvotes: 0
Reputation: 4911
Solved: the root of the problem was the fact that subsequent calls to logging.basicConfig do nothing, only the first call affects the basic config of the root handler. So nothing worked until I restarted the kernel in my notebook or something.
Upvotes: 15
Reputation: 2612
I've just tried your code in Jupyter Notebook. It ran just fine. I'm using Python 3.6 and this is on Windows 10:
In [1]: import logging
logging.basicConfig(filename='logs.log', level=logging.INFO)
logging.info('something happened')
In [2]: with open("logs.log") as log:
print(log.read())
INFO:root:something happened
Upvotes: 2
Reputation: 10899
Logging in Python is surprisingly difficult to configure - imo one of the worst libraries in the python universe. You might try the package logbook, which claims to have a better experience.
M.e. you are missing a call like this:
logger = logging.getlogger("mymodile")
logger.info("blub")
Sorry, I first ignored the bit about jupyter but that'S an important clue. JUpyter set's up a logger so it can capture logging for you and print it - but that disables basicConfig. This thread contains information about how to circumvent the problem: Get Output From the logging Module in IPython Notebook the answer from skulz00 seems to be ok.
Upvotes: 0