版权声明:Copyright reserved to Hazekiah Wang ([email protected]) https://blog.csdn.net/u010909964/article/details/84204758
I follow this guide and learned quite a bit.
Briefly speaking, to direct prompts to several destinations simultaneously requires the use of handlers. A handler is bound to one stream, and can be set log level and log format.
In the following code, I bind two handlers to the root logger. Each time logger.info()
is called, the information is directed to the bound handlers’ destinations according to their log level.
import logging
from sys import stdout
shdl = logging.StreamHandler(stdout)
shdl.setLevel(logging.WARNING)
fhdl = logging.FileHandler('logger.log')
fhdl.setLevel(logging.WARNING)
logging.basicConfig(format='%(asctime)s %(message)s',
handlers=[shdl, fhdl])
logger = logging.getLogger()
We can do more with logging. For example there is an demand for repeat experiemts for several times and each with its own log file.
The following code takes care of the replacement of fileHandler across experiments.
logger.handlers[1].close() # close the file
fhdl = logging.FileHandler('logger2.log')
fhdl.setLevel(logging.WARNING)
logger.handlers[1] = fhdl