My project is composed by a main.py main script and a module aaa.py . I've succesfully setup a log procedure by using the logging package in main.py, also specifying a log filename.
Which is the cleanest/"correct" way to let the functions contained in aaa.py to write in the same log file?
答案 0 :(得分:1)
Use the root logger in main.py by defining
logger = logging.getLogger()
fh = logging.FileHandler("path/to/file")
logger.addHandler(fh)
Then use a module logger in aaa.py by defining
logger = logging.getLogger(__name__)
The logger does not have to have the same name as the module, but it is common practice. The submodule logger will automatically bubble up to the root logger and be sent to any handlers.
To quote from the docs
Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed.
答案 1 :(得分:0)
If you call only a single python script at once (main.py)
then you simply can define your logging config once; for exemple:
logging.basicConfig(filename=logfilepath, format='%(levelname)s:%(message)s')
and call it wherever you want in the modules, for exemple
logging.<level>("log_string")