I have a main file where I use all the functions from the module. I want to log all the necessary things into file and into stdout.
It works when I use logger.info("Write it into file")
inside main file, but it doesn’t work when I import here some functions from the other scripts.
I use it inside main file to make a logger
JavaScript
x
16
16
1
logger = logging.getLogger(__name__)
2
logger.setLevel(logging.INFO)
3
# create file handler
4
fh = logging.FileHandler('logging.log', mode='a')
5
fh.setLevel(logging.DEBUG)
6
# create console handler
7
ch = logging.StreamHandler(sys.stdout)
8
ch.setLevel(logging.INFO)
9
# create formatter and add it to the handlers
10
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
11
fh.setFormatter(formatter)
12
ch.setFormatter(formatter)
13
# add the handlers to the logger
14
logger.addHandler(fh)
15
logger.addHandler(ch)
16
And in other file I use only
JavaScript
1
2
1
logger = logging.getLogger(__name__)
2
How can I get all the logs?
Advertisement
Answer
__name__
has different values in your two modules, so you really have two different loggers. You are only adding the file handler to one of them.
You want to configure a common ancestor. That could be the root logger:
JavaScript
1
5
1
root_logger = logging.getLogger()
2
3
root_logger.addHandler(fh)
4
root_logger.addHandler(ch)
5
or a specific logger that only your two loggers inherit from.
JavaScript
1
5
1
base_logger = logging.getLogger('base')
2
# configure base_logger
3
4
logger_in_main = logging.getLogger('base.' + __name__)
5
and
JavaScript
1
2
1
logger_in_other = logging.getLogger('base.' + __name__)
2