Search code examples
pythonloggingabseilabsl-py

Python absl logging without timestamp module name


I wanted to know if its possible to log only the msg string in absl python without timestamp and module name. Example

I0108 23:40:57.153055 140614090106688 extractor.py:79] processing file: dfcsdf
I0108 23:40:57.162382 140614090106688 extractor.py:72] ['/topic/fdfgd', dfgsdf']
I0108 23:40:57.162861 140614090106688 extractor.py:79] processing file: f456546fd
I0108 23:40:57.171764 140614090106688 extractor.py:72] ['/topic/1', '/topic/2', '/topic/3']

is there a configuration to log just message as below

processing file: dfcsdf
['/topic/fdfgd', dfgsdf']
processing file: f456546fd
['/topic/1', '/topic/2', '/topic/3']

I know I can replace the logging with print for console or write custom logger, I wanted to know if its possible in absl logging?


Solution

  • Setting formatter to None

    You can set the formatter to None. It may seem a bit tricky since it's not well documented (I had to read the source code to make sure this is is correct), but the following works:

    from absl import app
    from absl import logging
    
    
    def main(argv):
        logging.get_absl_handler().use_absl_log_file('log', "./FolderName")
    
        logging.get_absl_handler().setFormatter(None)
    
        logging.info('Info log')
        logging.warning('Warning log')
    
    if __name__ == '__main__':
        app.run(main)
    

    My log file looks like this after setting formatter to None:

    Info log

    Warning log

    Custom formatter

    That being said, implementing a custom formatter is not hard and I think is more elegant, plus it allows you to customize your output. You simply need to override the format function:

    from absl import app
    from absl import logging
    from absl.logging import PythonFormatter
    
    class CustomPythonFormatter(PythonFormatter):
        def format(self, record):
            return super(PythonFormatter, self).format(record)
    
    def main(argv):
        logging.get_absl_handler().use_absl_log_file('log', "./Folder")
    
        logging.get_absl_handler().setFormatter(CustomPythonFormatter())
    
        logging.info('Info log')
        logging.warning('Warning log')
    
    if __name__ == '__main__':
        app.run(main)
    

    This gives me the same result as before:

    Info log

    Warning log