I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there.
#!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(message)s',
handlers=[logging.FileHandler("example1.log"),
logging.StreamHandler()])
logging.debug('This message should go to the log file and to the console')
logging.info('So should this')
logging.warning('And this, too')
I have "bypassed" this problem by creating a logging object (example code), but it keeps bugging me why basicConfig() approach failed?
PS. If I change basicConfig call to:
logging.basicConfig(level=logging.DEBUG,
filename="example2.log",
format='%(asctime)s %(message)s',
handlers=[logging.StreamHandler()])
Then all logs are in the file and nothing is displayed in the console
In the example below, you can specify the log destination based on its level. For example, the code below lets all logs over the INFO level go to the log file, and all above ERROR level goes to the console.
Reusable logger function.
On Other python file, import the
logger
I can't reproduce it on Python 3.3. The messages are written both to the screen and the
'example2.log'
. On Python <3.3 it creates the file but it is empty.The code:
shows that
FileHandler()
is not attached to the root logger on Python <3.3.The docs for
logging.basicConfig()
say thathandlers
argument is added in Python 3.3. Thehandlers
argument isn't mentioned in Python 3.2 documentation.Try this working fine(tested in python 2.7) for both console and file