Reputation: 57
import logging
#Create and configure logger
logging.basicConfig(filename="newfile.txt", format='%(asctime)s %(message)s',filemode='w')
logging.debug("Harmless debug Message")
logging.info("Just an information")
logging.warning("Its a Warning")
logging.error("Did you try to divide by zero")
logging.critical("Internet is down")
In the console its printing all these informations. Its never written to a file. Really thankful to those help me sort out this. Searching in internet from morning tried all the possibilities but still the logs not writing to file
Upvotes: 1
Views: 4521
Reputation: 116
Create an new logger with desired stream & file handlers:
import logger, sys
logger = logging.Logger('AmazeballsLogger')
#Stream/console output
logger.handler = logging.StreamHandler(sys.stdout)
logger.handler.setLevel(logging.WARNING)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
logger.handler.setFormatter(formatter)
logger.addHandler(self.handler)
#File output
fh = logging.FileHandler("test.log")
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
logger.addHandler(fh)
And you're ready to take it for a spin:
print(logger.handlers)
logger.critical("critical")
logger.error("error")
logger.warning("warning")
logger.info("info")
logger.debug("debug")
With the following console output only showing WARNING and higher:
[<StreamHandler stdout (WARNING)>, <FileHandler C:\Users\...\test.log (DEBUG)>]
2020-04-13 17:52:57,729 - CRITICAL - critical
2020-04-13 17:52:57,731 - ERROR - error
2020-04-13 17:52:57,734 - WARNING - warning
While test.log contains all levels:
2020-04-13 17:52:57,729 - AmazeballsLogger - CRITICAL - critical
2020-04-13 17:52:57,731 - AmazeballsLogger - ERROR - error
2020-04-13 17:52:57,734 - AmazeballsLogger - WARNING - warning
2020-04-13 17:52:57,736 - AmazeballsLogger - INFO - info
2020-04-13 17:52:57,736 - AmazeballsLogger - DEBUG - debug
The key is to understand how logging handlers work and checking whether they use correct levels (as in the code cells above, just print logger.handlers). Furthermore, overwriting basic configuration is a bad practice that can lead to problems when you run multiple loggers in the same python environment. I recommend this video, it sheds light on stream/file handlers in python logging.
Upvotes: 3
Reputation: 332
I got this example from logging documentation
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename='myapp.log',
filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')
and the examples that I have seen on the web they are all creating .log
file. So try changing the extension of file from txt to log
Upvotes: 2