When I write new experimental code, I always forget the magic around logging, so I write it so that I can copy it.
It is assumed that the situation is as follows.
Write the following in the file of the library.
The logging level for this file only is set at logger.setLevel (log.INFO)
. (Useful when you want to debug each function)
module.py
import logging as log
#Logger settings for each file
logger = log.getLogger(__name__)
logger.setLevel(log.INFO) #Change the display level for each module
def func():
logger.info("From module.func()")
logger.info("Key1\tValue")
logger.debug("This is not displayed")
And for the main script that imports and uses this library, write as follows.
The definition around formatter
is your choice. Tab-separating the message and earlier, as in this example, will make it easier to process the log file later.
** 2020/06/03 Fix: It seems that the level of the log to be displayed had to be set on the handler side, so I fixed it that way. ** **
main.py
import logging as log
import module
#Logger settings for each file
logger = log.getLogger(__name__)
if __name__=="__main__":
formatter = "[%(asctime)s] %(levelname)s - %(name)s\t%(message)s"
handlers = [log.StreamHandler(), log.FileHandler("logfile")]
for handler in handlers:
handler.setLevel(log.INFO) #Level of log to display
log.basicConfig(
level = log.DEBUG, format = formatter, handlers = handlers
)
#Log output
logger.info("Call module.func() from main.")
module.func()
logger.debug("This is displayed")
The following logs are output to standard output and file respectively. It is convenient because you can see which file the log was sent from.
[2020-05-15 12:39:20,676] INFO - __main__ Call module.func() from main.
[2020-05-15 12:39:20,677] INFO - module From module.func()
[2020-05-15 12:39:20,678] INFO - module Key1 Value
[2020-05-15 12:39:20,680] DEBUG - __main__This is displayed
Recommended Posts