question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

integrating loguru with Flask and/or Celery loggers

See original GitHub issue

I really like loguru and it simplifies my whole setup. I have a hacked custom Logger that I use in my code and Flask webapps. I’d like to replace it with loguru, since it basically does the things I hacked. What’s the procedure to properly integrate loguru into other apps that might have loggers based on the standard logger?

This is what I’ve done to integrate loguru into my code and Flask web app, and the error I am getting.

#Function to initialize a loguru logger
def initLog(logpath):
    ''' test loguru '''
    from loguru import logger
    import sys
    import logging

    logger.add(sys.stderr, format="{level} | {message} ",
               level="INFO", colorize=True, enqueue=True, backtrace=True)

    fmt = "{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message} [{function} @ {file}]"
    logger.add("logtest.log", rotation='10 seconds', format=fmt,
               colorize=True, backtrace=True, enqueue=True)

    new_level = logger.level("IMPORTANT", no=25, color="<magenta>")

    # capture warnings
    showwarning_ = warnings.showwarning

    def showwarning(message, *args, **kwargs):
        logger.warning(message)
        showwarning_(message, *args, **kwargs)

    warnings.showwarning = showwarning

    # propagate to standard logger
    class PropagateHandler(logging.Handler):
        def emit(self, record):
            logging.getLogger(record.name).handle(record)

    logger.add(PropagateHandler(), format="{message}")

    return logger

Then I’m trying to integrate it into my Flask webapp

log = initLog('testlog.log')

app = Flask()
# add custom logger to the Flask app
app.logger.addHandler(log)

# use the Flask logger to log messages
app.logger.info('Loading Development Config!')

but I get the following error:

    app.logger.info('Loading Development Config!')
  File "/Users/Brian/anaconda3/lib/python3.7/logging/__init__.py", line 1375, in info
    Log 'msg % args' with severity 'INFO'.
  File "/Users/Brian/anaconda3/lib/python3.7/logging/__init__.py", line 1383, in info
    self._log(INFO, msg, args, **kwargs)
  File "/Users/Brian/anaconda3/lib/python3.7/logging/__init__.py", line 1519, in _log
    self.handle(record)
  File "/Users/Brian/anaconda3/lib/python3.7/logging/__init__.py", line 1529, in handle
    self.callHandlers(record)
  File "/Users/Brian/anaconda3/lib/python3.7/logging/__init__.py", line 1590, in callHandlers
    if record.levelno >= hdlr.level:
TypeError: '>=' not supported between instances of 'int' and 'method'

What’s the correct way to integrate loguru into other libraries like Flask or Celery?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Delgancommented, Aug 27, 2019

Hey @havok2063.

I think a confusion between “handler” and “logger” may explain the error you are seeing. The logger is a basic object to use when you want to write a log message. Handlers are objects which are in charge or receiving this log messages, and processing adequately: write it on stderr, write it in a file, send it by email, etc.

A logger has methods like .info(), .debug() and .warning() while an handler has methods like .write() and .emit().

So, when you use app.logger.addHandler(log), you pass a logger object while Flask expects an handler, hence bug occurs. 😄

Maybe you can try to use an InterceptHandler() instead, which should send Flask’s logs back to Loguru’s handlers:

class InterceptHandler(logging.Handler):
    def emit(self, record):
        # Retrieve context where the logging call occurred, this happens to be in the 6th frame upward
        logger_opt = logger.opt(depth=6, exception=record.exc_info)
        logger_opt.log(record.levelno, record.getMessage())
handler = InterceptHandler()
handler.setLevel(0)
app.logger.addHandler(handler)
0reactions
Delgancommented, Oct 8, 2019

I’m closing this since it seems I answered the initial question. Be sure that I will work on the C implementation as soon as possible. 😄

Read more comments on GitHub >

github_iconTop Results From Across the Web

Logging with flask and celery - Google Groups
I'm trying to understand how to integrate flask logging with celery. I have a custom error handler that send every exception with mandrill....
Read more >
Duplicate Celery logs in a Flask app - phdesign
Within my Celery task module, I get the logger as a global variable. # @myapp/tasks/alerts.py from celery.utils.log import get_task_logger ...
Read more >
3 Strategies to Customise Celery logging handlers
In this post I'll show you three alternative strategies to configure your Celery loggers and explain how and why each strategy works.
Read more >
Celery logger configuration - python - Stack Overflow
For what it's worth, this is how I configured celery to use my Django logging settings: from __future__ import absolute_import, ...
Read more >
Using Celery With Flask - miguelgrinberg.com
The integration of Celery with Flask is so simple that no extension is required. A Flask application that uses Celery needs to initialize ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found