Logging to a file log
I’m trying to save all my log messages to a file instead of displaying it on the console. Here’s the code I used:
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s" logging.basicConfig( level = 'DEBUG', filename = 'debug.log', format = LOG_FORMAT) logger = logging.getLogger('jn') logger.warning('Testing warning') logger.debug('Testing debug')
The level kwargs seems to be the only one that get passed on because I get the debug and warning outputs in the console and not in the file, and it is not formatted as specified.
If anybody has any good reference for the use of the os module with Pythonista, I would take it as well. It doesn’t seem like we have all the permissions to do what we want with that module.
Thanks for your help,
@jnbris, sadly, I gave up on the logging module on Pythonista years ago since I found it very unintuitive and in any case overkill for the typical Pythonista projects. Depending on your requirements, a simple custom version with an identical api would not be much more than 10 lines.
I am not aware of any specific Pythonista os module reference. Which capabilities are you after?
one problem with the logging module when used in a repl environment like pythonista is that when you rerun a script, it creates a new logger instance... so you need to have some extra logic.
here is the little cookbook that i use in pythonista:
import logging, sys logger = logging.getLogger('myapp') if not logger.handlers: filehdlr = logging.FileHandler('myapp.txt','w') strmhandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') filehdlr.setFormatter(formatter) strmhandler.setFormatter(formatter) logger.addHandler(filehdlr) logger.addHandler(strmhandler) filehdlr.setLevel(logging.DEBUG) strmhandler.setLevel(logging.INFO) logger.setLevel(logging.DEBUG) % examples logger.debug('this gets logged to file only') logger.info('this shows to screen and file')