python - Logging Handlers: How do I make sure I am not making two? -
edit: ended answering beef of question can have working logging module. however, still have related question. see answer below.
i trying implement logging logging temporary directory of whatever os in. have written following function.
import logging, tempfile, os, sys def getlog(logname, filename = 'python.log', directory = none): '''returns logger logname print filename , directoryname.''' if directory == none: fd, fname = tempfile.mkstemp() directory = os.path.dirname(fname) fullpath = directory + '/' + filename mylog = logging.getlogger(logname) hdlr = logging.filehandler(fullpath) formatter = logging.formatter('l:%(name)s m:%(module)s t:%(asctime)s > %(levelname)s: %(message)s') hdlr.setformatter(formatter) mylog.addhandler(hdlr) mylog.setlevel(logging.info) mylog.info('new logger started') return mylog if __name__ == '__main__': log = getlog('testing') log.info('working?') log.info('yes, seems working') log2 = getlog('testing') log2.info('still working?') here output:
l:testing m:easy_log t:2011-04-11 15:30:14,315 > info: new logger started l:testing m:easy_log t:2011-04-11 15:30:14,316 > info: working? l:testing m:easy_log t:2011-04-11 15:30:14,316 > info: yes, seems working l:testing m:easy_log t:2011-04-11 15:30:14,316 > info: new logger started l:testing m:easy_log t:2011-04-11 15:30:14,316 > info: new logger started l:testing m:easy_log t:2011-04-11 15:30:14,316 > info: still working? l:testing m:easy_log t:2011-04-11 15:30:14,316 > info: still working? as can see, outputting double. however, logging module rather confusing, , not know of way find out if log has been instantiated, or if log object has handler. appreciated.
edit: add little more detail, planning on calling in several modules, trying replace "logging.getlogger" call.
i ended answering own question. here code
global is_setup is_setup = false def setuplogger(filename = 'python.log', directory = none, format = 'l:%(name)s m:%(module)s t:%(asctime)s > %(levelname)s: %(message)s'): global is_setup if directory == none: fd, fname = tempfile.mkstemp() directory = os.path.dirname(fname) logging.basicconfig(filename = directory + '/' + filename, format = format) is_setup = true def getlog(logname, level = logging.info): '''returns logger logname print filename , directoryname.''' if is_setup == false: setuplogger() mylog = logging.getlogger(logname) mylog.setlevel(level) mylog.info('new logger started') return mylog this avoids double config. also, apparently basic config work if called multiple times.
if knows how check handlers on log object, still know. seems absolutely impossible.
Comments
Post a Comment