Search code examples
pythonloggingstdoutstderr

Redirect Python sublibrary output to logger


I am currently using Pythons logging module to log output to a file and also print it into the console. My problem is that some sublibraries are also writing output to the console, which is not captured by my logger. An example output would be:

2022-06-08 16:18:16,990 [INFO] - Main code started
blablabla
2022-06-08 16:18:16,990 [INFO] - Main code finished

How can I manage to have this blablabla output captured by the logger as well, without having access to the source code of the sublibrary?


Solution

  • First you need to make sure the libraries are really using the logger and not just print. From the output it looks like they are using print because the line is not formatted like the other log messages.

    If they use the logger, you can simply get the logger via:

    import logging
    
    other_logger = logging.getLogger(...)
    # do something with other logger
    
    

    and configure it appropriately.

    If they use just print, then you don't have much left to do.