Where to store the log file name in python?

I have a Python program consisting of several modules. The "main" module creates a log_file file variable to register output; all other modules will also have to be written to this file.

However, I do not want to import the β€œmain” module into other modules, since this will be a very strange dependency (not to mention that it may not even work due to a cyclic dependency).

Where should I store the log_file variable?

EDIT:

After @pyfunc answer - this will be fine:

 --- config.py --- # does not mention log_file # unless it required for syntax reasons; in which case log_file = None # ... --- main.py --- from datetime import datetime import config.py log_filename = str(datetime.now()) + '.txt' config.log_file = open(log_filename, 'w') # ... --- another_module.py --- import config.py # ... config.log_file.write(some_stuff) 
+4
python module
source share
2 answers

One way is to take all this code into another module so that you can import it into the main file and other modules.

Hope you checked: http://docs.python.org/library/logging.html

+1
source share

Place the "global" variable in the "settings" module.

settings.py

 log_file = "/path/to/file" 

main.py

 import settings import logging logging.basicConfig(filename=settings.log_file,level=logging.DEBUG) logging.debug("This should go to the log file") 

other_module.py

 import logging logging.debug("This is a message from another place.") 

While the log module can solve your immediate problem and many others, the settings module template is useful for many other things besides the log file names. It is used by Django to configure almost everything.

+2
source share

All Articles