Two questions about logging
Matthew Pounsett
matt.pounsett at gmail.com
Sat Jan 14 21:03:20 EST 2012
On Jan 12, 8:03 pm, K Richard Pixley <r... at noir.com> wrote:
> Here's the confusion. Each log named __name__ is under the root logger.
> If you want them all, then catch them all with the root logger.
Thanks! I knew I was missing something obvious. Between you and Jean-
Michael Pichavant I've figured out what I need to do here.
On Jan 11, 9:34 pm, Roy Smith <r... at panix.com> wrote:
> What I would do is log to syslog (logging.handlers.SysLogHandler) and
> let syslog worry about rotating log files. Why reinvent the wheel?
I've also worked out what I need to reset file handles, although it
took a lot of reading in the various logging.Handler subclasses. What
I needed isn't explicitly documented anywhere, but it turns out that
calling the close() method on a FileHandler instance does what I
need. There's no method to re-open the handler, but the next call to
emit() will automatically re-open the file if it isn't already open.
The upshot is that this does the expected thing if you rename its log
file and then send the running script a HUP signal.
#!/usr/bin/env python
import logging
import signal
import time
logger = logging.getLogger()
lh = logging.FileHandler('./foo.log')
lh.setFormatter(logging.Formatter('%(asctime)s %(name)s: %(message)s',
'%T'))
logger.addHandler(lh)
def sighup(signum, frame):
lh.close()
logger.error("handled {0}: {1}".format(signum, frame))
def main():
signal.signal(signal.SIGHUP, sighup)
while 1:
time.sleep(1)
logger.error('a message')
if __name__ == '__main__':
main()
More information about the Python-list
mailing list