Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No handlers could be found for logger "__main__"

Tags:

python

logging

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()
like image 606
Liondancer Avatar asked Apr 04 '16 18:04

Liondancer


2 Answers

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

like image 77
hspandher Avatar answered Nov 15 '22 06:11

hspandher


You can set the handler for a specific this way:

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

Or set basic configuration for all loggers:

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

like image 34
oxidworks Avatar answered Nov 15 '22 04:11

oxidworks