Reputation: 729
This is a scenario where a module contains a Logger and it is being imported into another module. When main.py is called however, no LogRecords are written to the log. What can be revised in order for the log to be called?
#objects.py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter()
log_handler = logging.FileHandler('log_objects.log')
log_handler.setFormatter(formatter)
logger.addHandler(log_handler)
class Person:
def __init__(self):
pass
logger.info(f"A new {self.__class__.__name__} is created.")
#main.py
from my_objects import objects
if __name__ == '__main__':
objects.Person()
-dir/
-my_objects/
__init__.py
log_objects.log
objects.py
-main.py
I'm expecting to see this in the log:
"A new Person is created."
Upon execution nothing shows in the log
Upvotes: 0
Views: 33
Reputation: 21
It works as expected. 'log_objects.log' is got created with valid line. Are you expecting the text to be printed on the console as well? Once specific file handler is added the default handler will be overwritten.
(or) You possibly missing that how module load happens in python
$ python main.py
$ tree .
.
├── log_objects.log
├── main.py
└── my_objects
├── __init__.py
└── objects.py
$ cat log_objects.log
A new Person is created.
Upvotes: 0
Reputation: 106553
Since you do not specify a path name for log_objects.log
, the file will be created under the directory where the Python interpreter is run, which in this case, is where main.py
is located, rather than under the my_objects
sub-directory.
If you want log_objects.log
to be created under the my_objects
directory, you can specify a relative path:
log_handler = logging.FileHandler('my_objects/log_objects.log')
Upvotes: 1