Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- How to flush the log? (django)

I'm working with Django-nonrel on Google App Engine, which forces me to use logging.debug() instead of print().

The "logging" module is provided by Django, but I'm having a rough time using it instead of print().

For example, if I need to verify the content held in the variable x, I will put
logging.debug('x is: %s' % x). But if the program crashes soon after (without flushing the stream), then it never gets printed.

So for debugging, I need debug() to be flushed before the program exits on error, and this is not happening.

like image 427
Rucent88 Avatar asked Nov 01 '12 11:11

Rucent88


People also ask

What does flushing a log mean?

To force all buffered output to a particular log file, use the flush command. This lets you examine a current log file offline while the normal log file is still open. Note: Alarm logs are always flushed. This means that the alarm output is always sent to the log file immediately.

Where do Django logs go?

The Django One-Click application employs Gunicorn and Upstart. Application level logging can be found in /var/log/upstart/gunicorn. log By default, Gunicorn logs to stderr and Upstart will collect output to stderr/stdout in /var/log/upstart/$JOB_NAME.

What is Python log debugging?

logging.debug() Diagnose problems, show detailed information. The logging module sets the default level at WARNING , so WARNING , ERROR , and CRITICAL will all be logged by default.


2 Answers

I think this may work for you, assuming you're only using one(or default) handler:

>>> import logging >>> logger = logging.getLogger() >>> logging.debug('wat wat') >>> logger.handlers[0].flush() 

It's kind of frowned upon in the documentation, though.

Application code should not directly instantiate and use instances of Handler. Instead, the Handler class is a base class that defines the interface that all handlers should have and establishes some default behavior that child classes can use (or override). http://docs.python.org/2/howto/logging.html#handler-basic

And it could be a performance drain, but if you're really stuck, this may help with your debugging.

like image 174
Mike Shultz Avatar answered Sep 20 '22 20:09

Mike Shultz


I struggled with a similar problem and here is how I solved it. Instead of using logging module directly to output your logs, initialize your own logger as follows:

import sys import logging   def init_logger():     logger = logging.getLogger()      h = logging.StreamHandler(sys.stdout)     h.flush = sys.stdout.flush     logger.addHandler(h)      return logger 

Then, use it instead of logging in your code:

def f():     logger = init_logger()     logger.debug('...') 

As a result, you won't have problems with flushing logs anymore.

like image 31
constt Avatar answered Sep 20 '22 20:09

constt