I am getting this logger error and I'm not sure how this occurred. I created much simpler test programs and they worked. Any thoughts where this error could be coming from?
Running this program in python 2.6!
error:
No handlers could be found for logger "__main__"
code:
import logging
import subprocess as sp
logger = logging.getLogger(__name__)
def runpig(filename):
# does not use logger
....
....
return
def main():
try:
runpig(filename)
except sp.CalledProcessError as ex:
logger.error(ex.message)
except:
logger.info("Error occured")
if __name__ == "__main__":
main()
答案 0 :(得分:8)
You either need to call logging.basicConfig
first or just call logging.info
which would automatically call it.
if __name__ == "__main__":
logging.info("Begin")
main()
That should work
答案 1 :(得分:1)
您可以通过以下方式设置处理程序:
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(name)s (%(lineno)s) - %(levelname)s: %(message)s", datefmt='%Y.%m.%d %H:%M:%S')
handler.setFormatter(formatter)
logger.addHandler(handler)
https://stackoverflow.com/a/26258712/1907997 https://docs.python.org/2/library/logging.html#logging.Logger.addHandler
或者为所有记录器设置基本配置:
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s (%(lineno)s) - %(levelname)s: %(message)s", datefmt='%Y.%m.%d %H:%M:%S')
https://docs.python.org/2/library/logging.html#logging.basicConfig