24

I've got a project where I'm using Twisted for my web server. When exceptions occur (such as network errors), it's printing to the console.

I've already got logging through Python's built-in log module - is there any way to tell the reactor to use that instead?

What's the usual pattern for this?

Dave
  • 2,029
  • 2
  • 21
  • 30

2 Answers2

25

Found it. It's actually quite easy:

from twisted.python import log
observer = log.PythonLoggingObserver(loggerName='logname')
observer.start()

You just set loggerName to the same logger name that you're using in logging.getLogger().

Dave
  • 2,029
  • 2
  • 21
  • 30
  • 2
    Note that you aren't required to use the same loggerName. Using a different one may help distinguish where log messages are coming from and is equivalent to using different loggers in different parts of your application. – Nicola Musatti Jun 07 '12 at 13:55
  • That's a good idea. What also helps is that I include the thread name in the log message format. That helps when figuring out where logs are coming from. – Dave Jun 08 '12 at 14:40
  • 1
    Just FYI the python logging module can block and twisted does not expect that. Better way is to write customer handler in python, that calls sends events to twisted. This way you time python locking logging to nonblocking one – Sedy Vlk Nov 10 '17 at 16:32
  • @LaKantara Thank you! But please, can you elaborate that? Perhaps in a separate answer how this might look like? (Sorry, I do not have 1++ year to learn everything about twisted, just to be able to understand how that, what you suggest, can be archived, only to be able to integrate some major "twisted infected" source into something like a non-twisted framework.) – Tino Nov 16 '17 at 11:07
2

You can use twisted.python.log. For example:

from twisted.python import log
log.msg('Hello, world.')
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • 2
    This does work, but only for your own log messages, not the ones generated by twisted and its modules. – fiorix Jul 06 '12 at 18:14