+try:\r
+ from logging.handlers import QueueHandler\r
+except:\r
+ class QueueHandler(logging.Handler):\r
+ """\r
+ This handler sends events to a queue. Typically, it would be used together\r
+ with a multiprocessing Queue to centralise logging to file in one process\r
+ (in a multi-process application), so as to avoid file write contention\r
+ between processes.\r
+\r
+ This code is new in Python 3.2, but this class can be copy pasted into\r
+ user code for use with earlier Python versions.\r
+ """\r
+\r
+ def __init__(self, queue):\r
+ """\r
+ Initialise an instance, using the passed queue.\r
+ """\r
+ logging.Handler.__init__(self)\r
+ self.queue = queue\r
+\r
+ def enqueue(self, record):\r
+ """\r
+ Enqueue a record.\r
+\r
+ The base implementation uses put_nowait. You may want to override\r
+ this method if you want to use blocking, timeouts or custom queue\r
+ implementations.\r
+ """\r
+ self.queue.put_nowait(record)\r
+\r
+ def prepare(self, record):\r
+ """\r
+ Prepares a record for queuing. The object returned by this method is\r
+ enqueued.\r
+\r
+ The base implementation formats the record to merge the message\r
+ and arguments, and removes unpickleable items from the record\r
+ in-place.\r
+\r
+ You might want to override this method if you want to convert\r
+ the record to a dict or JSON string, or send a modified copy\r
+ of the record while leaving the original intact.\r
+ """\r
+ # The format operation gets traceback text into record.exc_text\r
+ # (if there's exception data), and also returns the formatted\r
+ # message. We can then use this to replace the original\r
+ # msg + args, as these might be unpickleable. We also zap the\r
+ # exc_info and exc_text attributes, as they are no longer\r
+ # needed and, if not None, will typically not be pickleable.\r
+ msg = self.format(record)\r
+ record.message = msg\r
+ record.msg = msg\r
+ record.args = None\r
+ record.exc_info = None\r
+ record.exc_text = None\r
+ return record\r
+\r
+ def emit(self, record):\r
+ """\r
+ Emit a record.\r
+\r
+ Writes the LogRecord to the queue, preparing it for pickling first.\r
+ """\r
+ try:\r
+ self.enqueue(self.prepare(record))\r
+ except Exception:\r
+ self.handleError(record)\r