简体   繁体   中英

Redefining logging root logger

At my current project there are thousand of code lines which looks like this:

logging.info("bla-bla-bla")

I don't want to change all these lines, but I would change log behavior. My idea is changing root logger to other Experimental logger, which is configured by ini-file:

[loggers]
keys =  Experimental

[formatter_detailed]
format = %(asctime)s:%(name)s:%(levelname)s %(module)s:%(lineno)d:  %(message)s

[handler_logfile]
class = FileHandler
args = ('experimental.log', 'a')
formatter = detailed

[logger_Experimental]
level = DEBUG
qualname = Experimental
handlers = logfile
propagate = 0

Now setting the new root logger is done by this piece of code:

logging.config.fileConfig(path_to_logger_config)
logging.root = logging.getLogger('Experimental')

Is redefining of root logger safe? Maybe there is more convenient way?

I've tried to use google and looked through stackoverflow questions, but I didn't find the answer.

You're advised not to redefine the root logger in the way you describe. In general you should only use the root logger directly for small scripts - for larger applications, best practice is to use

logger = logging.getLogger(__name__)

in each module where you use logging, and then make calls to logger.info() etc.

If all you want to do is to log to a file, why not just add a file handler to the root logger? You can do using eg

if __name__ == '__main__':
    logging.basicConfig(filename='experimental.log', filemode='w')
    main() # or whatever your main entry point is called

or via a configuration file.

Update: When I say "you're advised", I mean by me, here in this answer ;-) While you may not run into any problems in your scenario, it's not good practice to overwrite a module attribute which hasn't been designed to be overwritten. For example, the root logger is an instance of a different class (which is not part of the public API), and there are other references to it in the logging machinery which would still point to the old value. Either of these facts could lead to hard-to-debug problems. Since the logging package allows a number of ways of achieving what you seem to want (seemingly, logging to a file rather than the console), then you should use those mechanisms that have been provided.

logger = logging.getLogger() Leaving the name empty will return you the root logger.

logger = logging.getLogger('name') Gives you another logger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM