handlers.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. # Copyright 2001-2013 by Vinay Sajip. All Rights Reserved.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose and without fee is hereby granted,
  5. # provided that the above copyright notice appear in all copies and that
  6. # both that copyright notice and this permission notice appear in
  7. # supporting documentation, and that the name of Vinay Sajip
  8. # not be used in advertising or publicity pertaining to distribution
  9. # of the software without specific, written prior permission.
  10. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  11. # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  13. # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. Additional handlers for the logging package for Python. The core package is
  18. based on PEP 282 and comments thereto in comp.lang.python.
  19. Copyright (C) 2001-2013 Vinay Sajip. All Rights Reserved.
  20. To use, simply 'import logging.handlers' and log away!
  21. """
  22. import errno, logging, socket, os, cPickle, struct, time, re
  23. from stat import ST_DEV, ST_INO, ST_MTIME
  24. try:
  25. import codecs
  26. except ImportError:
  27. codecs = None
  28. try:
  29. unicode
  30. _unicode = True
  31. except NameError:
  32. _unicode = False
  33. #
  34. # Some constants...
  35. #
  36. DEFAULT_TCP_LOGGING_PORT = 9020
  37. DEFAULT_UDP_LOGGING_PORT = 9021
  38. DEFAULT_HTTP_LOGGING_PORT = 9022
  39. DEFAULT_SOAP_LOGGING_PORT = 9023
  40. SYSLOG_UDP_PORT = 514
  41. SYSLOG_TCP_PORT = 514
  42. _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
  43. class BaseRotatingHandler(logging.FileHandler):
  44. """
  45. Base class for handlers that rotate log files at a certain point.
  46. Not meant to be instantiated directly. Instead, use RotatingFileHandler
  47. or TimedRotatingFileHandler.
  48. """
  49. def __init__(self, filename, mode, encoding=None, delay=0):
  50. """
  51. Use the specified filename for streamed logging
  52. """
  53. if codecs is None:
  54. encoding = None
  55. logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  56. self.mode = mode
  57. self.encoding = encoding
  58. def emit(self, record):
  59. """
  60. Emit a record.
  61. Output the record to the file, catering for rollover as described
  62. in doRollover().
  63. """
  64. try:
  65. if self.shouldRollover(record):
  66. self.doRollover()
  67. logging.FileHandler.emit(self, record)
  68. except (KeyboardInterrupt, SystemExit):
  69. raise
  70. except:
  71. self.handleError(record)
  72. class RotatingFileHandler(BaseRotatingHandler):
  73. """
  74. Handler for logging to a set of files, which switches from one file
  75. to the next when the current file reaches a certain size.
  76. """
  77. def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
  78. """
  79. Open the specified file and use it as the stream for logging.
  80. By default, the file grows indefinitely. You can specify particular
  81. values of maxBytes and backupCount to allow the file to rollover at
  82. a predetermined size.
  83. Rollover occurs whenever the current log file is nearly maxBytes in
  84. length. If backupCount is >= 1, the system will successively create
  85. new files with the same pathname as the base file, but with extensions
  86. ".1", ".2" etc. appended to it. For example, with a backupCount of 5
  87. and a base file name of "app.log", you would get "app.log",
  88. "app.log.1", "app.log.2", ... through to "app.log.5". The file being
  89. written to is always "app.log" - when it gets filled up, it is closed
  90. and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
  91. exist, then they are renamed to "app.log.2", "app.log.3" etc.
  92. respectively.
  93. If maxBytes is zero, rollover never occurs.
  94. """
  95. # If rotation/rollover is wanted, it doesn't make sense to use another
  96. # mode. If for example 'w' were specified, then if there were multiple
  97. # runs of the calling application, the logs from previous runs would be
  98. # lost if the 'w' is respected, because the log file would be truncated
  99. # on each run.
  100. if maxBytes > 0:
  101. mode = 'a'
  102. BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  103. self.maxBytes = maxBytes
  104. self.backupCount = backupCount
  105. def doRollover(self):
  106. """
  107. Do a rollover, as described in __init__().
  108. """
  109. if self.stream:
  110. self.stream.close()
  111. self.stream = None
  112. if self.backupCount > 0:
  113. for i in range(self.backupCount - 1, 0, -1):
  114. sfn = "%s.%d" % (self.baseFilename, i)
  115. dfn = "%s.%d" % (self.baseFilename, i + 1)
  116. if os.path.exists(sfn):
  117. #print "%s -> %s" % (sfn, dfn)
  118. if os.path.exists(dfn):
  119. os.remove(dfn)
  120. os.rename(sfn, dfn)
  121. dfn = self.baseFilename + ".1"
  122. if os.path.exists(dfn):
  123. os.remove(dfn)
  124. # Issue 18940: A file may not have been created if delay is True.
  125. if os.path.exists(self.baseFilename):
  126. os.rename(self.baseFilename, dfn)
  127. if not self.delay:
  128. self.stream = self._open()
  129. def shouldRollover(self, record):
  130. """
  131. Determine if rollover should occur.
  132. Basically, see if the supplied record would cause the file to exceed
  133. the size limit we have.
  134. """
  135. if self.stream is None: # delay was set...
  136. self.stream = self._open()
  137. if self.maxBytes > 0: # are we rolling over?
  138. msg = "%s\n" % self.format(record)
  139. self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
  140. if self.stream.tell() + len(msg) >= self.maxBytes:
  141. return 1
  142. return 0
  143. class TimedRotatingFileHandler(BaseRotatingHandler):
  144. """
  145. Handler for logging to a file, rotating the log file at certain timed
  146. intervals.
  147. If backupCount is > 0, when rollover is done, no more than backupCount
  148. files are kept - the oldest ones are deleted.
  149. """
  150. def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):
  151. BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
  152. self.when = when.upper()
  153. self.backupCount = backupCount
  154. self.utc = utc
  155. # Calculate the real rollover interval, which is just the number of
  156. # seconds between rollovers. Also set the filename suffix used when
  157. # a rollover occurs. Current 'when' events supported:
  158. # S - Seconds
  159. # M - Minutes
  160. # H - Hours
  161. # D - Days
  162. # midnight - roll over at midnight
  163. # W{0-6} - roll over on a certain day; 0 - Monday
  164. #
  165. # Case of the 'when' specifier is not important; lower or upper case
  166. # will work.
  167. if self.when == 'S':
  168. self.interval = 1 # one second
  169. self.suffix = "%Y-%m-%d_%H-%M-%S"
  170. self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"
  171. elif self.when == 'M':
  172. self.interval = 60 # one minute
  173. self.suffix = "%Y-%m-%d_%H-%M"
  174. self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$"
  175. elif self.when == 'H':
  176. self.interval = 60 * 60 # one hour
  177. self.suffix = "%Y-%m-%d_%H"
  178. self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$"
  179. elif self.when == 'D' or self.when == 'MIDNIGHT':
  180. self.interval = 60 * 60 * 24 # one day
  181. self.suffix = "%Y-%m-%d"
  182. self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
  183. elif self.when.startswith('W'):
  184. self.interval = 60 * 60 * 24 * 7 # one week
  185. if len(self.when) != 2:
  186. raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
  187. if self.when[1] < '0' or self.when[1] > '6':
  188. raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
  189. self.dayOfWeek = int(self.when[1])
  190. self.suffix = "%Y-%m-%d"
  191. self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
  192. else:
  193. raise ValueError("Invalid rollover interval specified: %s" % self.when)
  194. self.extMatch = re.compile(self.extMatch)
  195. self.interval = self.interval * interval # multiply by units requested
  196. if os.path.exists(filename):
  197. t = os.stat(filename)[ST_MTIME]
  198. else:
  199. t = int(time.time())
  200. self.rolloverAt = self.computeRollover(t)
  201. def computeRollover(self, currentTime):
  202. """
  203. Work out the rollover time based on the specified time.
  204. """
  205. result = currentTime + self.interval
  206. # If we are rolling over at midnight or weekly, then the interval is already known.
  207. # What we need to figure out is WHEN the next interval is. In other words,
  208. # if you are rolling over at midnight, then your base interval is 1 day,
  209. # but you want to start that one day clock at midnight, not now. So, we
  210. # have to fudge the rolloverAt value in order to trigger the first rollover
  211. # at the right time. After that, the regular interval will take care of
  212. # the rest. Note that this code doesn't care about leap seconds. :)
  213. if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  214. # This could be done with less code, but I wanted it to be clear
  215. if self.utc:
  216. t = time.gmtime(currentTime)
  217. else:
  218. t = time.localtime(currentTime)
  219. currentHour = t[3]
  220. currentMinute = t[4]
  221. currentSecond = t[5]
  222. # r is the number of seconds left between now and midnight
  223. r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
  224. currentSecond)
  225. result = currentTime + r
  226. # If we are rolling over on a certain day, add in the number of days until
  227. # the next rollover, but offset by 1 since we just calculated the time
  228. # until the next day starts. There are three cases:
  229. # Case 1) The day to rollover is today; in this case, do nothing
  230. # Case 2) The day to rollover is further in the interval (i.e., today is
  231. # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
  232. # next rollover is simply 6 - 2 - 1, or 3.
  233. # Case 3) The day to rollover is behind us in the interval (i.e., today
  234. # is day 5 (Saturday) and rollover is on day 3 (Thursday).
  235. # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
  236. # number of days left in the current week (1) plus the number
  237. # of days in the next week until the rollover day (3).
  238. # The calculations described in 2) and 3) above need to have a day added.
  239. # This is because the above time calculation takes us to midnight on this
  240. # day, i.e. the start of the next day.
  241. if self.when.startswith('W'):
  242. day = t[6] # 0 is Monday
  243. if day != self.dayOfWeek:
  244. if day < self.dayOfWeek:
  245. daysToWait = self.dayOfWeek - day
  246. else:
  247. daysToWait = 6 - day + self.dayOfWeek + 1
  248. newRolloverAt = result + (daysToWait * (60 * 60 * 24))
  249. if not self.utc:
  250. dstNow = t[-1]
  251. dstAtRollover = time.localtime(newRolloverAt)[-1]
  252. if dstNow != dstAtRollover:
  253. if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
  254. addend = -3600
  255. else: # DST bows out before next rollover, so we need to add an hour
  256. addend = 3600
  257. newRolloverAt += addend
  258. result = newRolloverAt
  259. return result
  260. def shouldRollover(self, record):
  261. """
  262. Determine if rollover should occur.
  263. record is not used, as we are just comparing times, but it is needed so
  264. the method signatures are the same
  265. """
  266. t = int(time.time())
  267. if t >= self.rolloverAt:
  268. return 1
  269. #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
  270. return 0
  271. def getFilesToDelete(self):
  272. """
  273. Determine the files to delete when rolling over.
  274. More specific than the earlier method, which just used glob.glob().
  275. """
  276. dirName, baseName = os.path.split(self.baseFilename)
  277. fileNames = os.listdir(dirName)
  278. result = []
  279. prefix = baseName + "."
  280. plen = len(prefix)
  281. for fileName in fileNames:
  282. if fileName[:plen] == prefix:
  283. suffix = fileName[plen:]
  284. if self.extMatch.match(suffix):
  285. result.append(os.path.join(dirName, fileName))
  286. result.sort()
  287. if len(result) < self.backupCount:
  288. result = []
  289. else:
  290. result = result[:len(result) - self.backupCount]
  291. return result
  292. def doRollover(self):
  293. """
  294. do a rollover; in this case, a date/time stamp is appended to the filename
  295. when the rollover happens. However, you want the file to be named for the
  296. start of the interval, not the current time. If there is a backup count,
  297. then we have to get a list of matching filenames, sort them and remove
  298. the one with the oldest suffix.
  299. """
  300. if self.stream:
  301. self.stream.close()
  302. self.stream = None
  303. # get the time that this sequence started at and make it a TimeTuple
  304. currentTime = int(time.time())
  305. dstNow = time.localtime(currentTime)[-1]
  306. t = self.rolloverAt - self.interval
  307. if self.utc:
  308. timeTuple = time.gmtime(t)
  309. else:
  310. timeTuple = time.localtime(t)
  311. dstThen = timeTuple[-1]
  312. if dstNow != dstThen:
  313. if dstNow:
  314. addend = 3600
  315. else:
  316. addend = -3600
  317. timeTuple = time.localtime(t + addend)
  318. dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
  319. if os.path.exists(dfn):
  320. os.remove(dfn)
  321. # Issue 18940: A file may not have been created if delay is True.
  322. if os.path.exists(self.baseFilename):
  323. os.rename(self.baseFilename, dfn)
  324. if self.backupCount > 0:
  325. for s in self.getFilesToDelete():
  326. os.remove(s)
  327. if not self.delay:
  328. self.stream = self._open()
  329. newRolloverAt = self.computeRollover(currentTime)
  330. while newRolloverAt <= currentTime:
  331. newRolloverAt = newRolloverAt + self.interval
  332. #If DST changes and midnight or weekly rollover, adjust for this.
  333. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
  334. dstAtRollover = time.localtime(newRolloverAt)[-1]
  335. if dstNow != dstAtRollover:
  336. if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
  337. addend = -3600
  338. else: # DST bows out before next rollover, so we need to add an hour
  339. addend = 3600
  340. newRolloverAt += addend
  341. self.rolloverAt = newRolloverAt
  342. class WatchedFileHandler(logging.FileHandler):
  343. """
  344. A handler for logging to a file, which watches the file
  345. to see if it has changed while in use. This can happen because of
  346. usage of programs such as newsyslog and logrotate which perform
  347. log file rotation. This handler, intended for use under Unix,
  348. watches the file to see if it has changed since the last emit.
  349. (A file has changed if its device or inode have changed.)
  350. If it has changed, the old file stream is closed, and the file
  351. opened to get a new stream.
  352. This handler is not appropriate for use under Windows, because
  353. under Windows open files cannot be moved or renamed - logging
  354. opens the files with exclusive locks - and so there is no need
  355. for such a handler. Furthermore, ST_INO is not supported under
  356. Windows; stat always returns zero for this value.
  357. This handler is based on a suggestion and patch by Chad J.
  358. Schroeder.
  359. """
  360. def __init__(self, filename, mode='a', encoding=None, delay=0):
  361. logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  362. self.dev, self.ino = -1, -1
  363. self._statstream()
  364. def _statstream(self):
  365. if self.stream:
  366. sres = os.fstat(self.stream.fileno())
  367. self.dev, self.ino = sres[ST_DEV], sres[ST_INO]
  368. def emit(self, record):
  369. """
  370. Emit a record.
  371. First check if the underlying file has changed, and if it
  372. has, close the old stream and reopen the file to get the
  373. current stream.
  374. """
  375. # Reduce the chance of race conditions by stat'ing by path only
  376. # once and then fstat'ing our new fd if we opened a new log stream.
  377. # See issue #14632: Thanks to John Mulligan for the problem report
  378. # and patch.
  379. try:
  380. # stat the file by path, checking for existence
  381. sres = os.stat(self.baseFilename)
  382. except OSError as err:
  383. if err.errno == errno.ENOENT:
  384. sres = None
  385. else:
  386. raise
  387. # compare file system stat with that of our stream file handle
  388. if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
  389. if self.stream is not None:
  390. # we have an open file handle, clean it up
  391. self.stream.flush()
  392. self.stream.close()
  393. self.stream = None # See Issue #21742: _open () might fail.
  394. # open a new file handle and get new stat info from that fd
  395. self.stream = self._open()
  396. self._statstream()
  397. logging.FileHandler.emit(self, record)
  398. class SocketHandler(logging.Handler):
  399. """
  400. A handler class which writes logging records, in pickle format, to
  401. a streaming socket. The socket is kept open across logging calls.
  402. If the peer resets it, an attempt is made to reconnect on the next call.
  403. The pickle which is sent is that of the LogRecord's attribute dictionary
  404. (__dict__), so that the receiver does not need to have the logging module
  405. installed in order to process the logging event.
  406. To unpickle the record at the receiving end into a LogRecord, use the
  407. makeLogRecord function.
  408. """
  409. def __init__(self, host, port):
  410. """
  411. Initializes the handler with a specific host address and port.
  412. The attribute 'closeOnError' is set to 1 - which means that if
  413. a socket error occurs, the socket is silently closed and then
  414. reopened on the next logging call.
  415. """
  416. logging.Handler.__init__(self)
  417. self.host = host
  418. self.port = port
  419. self.sock = None
  420. self.closeOnError = 0
  421. self.retryTime = None
  422. #
  423. # Exponential backoff parameters.
  424. #
  425. self.retryStart = 1.0
  426. self.retryMax = 30.0
  427. self.retryFactor = 2.0
  428. def makeSocket(self, timeout=1):
  429. """
  430. A factory method which allows subclasses to define the precise
  431. type of socket they want.
  432. """
  433. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  434. if hasattr(s, 'settimeout'):
  435. s.settimeout(timeout)
  436. s.connect((self.host, self.port))
  437. return s
  438. def createSocket(self):
  439. """
  440. Try to create a socket, using an exponential backoff with
  441. a max retry time. Thanks to Robert Olson for the original patch
  442. (SF #815911) which has been slightly refactored.
  443. """
  444. now = time.time()
  445. # Either retryTime is None, in which case this
  446. # is the first time back after a disconnect, or
  447. # we've waited long enough.
  448. if self.retryTime is None:
  449. attempt = 1
  450. else:
  451. attempt = (now >= self.retryTime)
  452. if attempt:
  453. try:
  454. self.sock = self.makeSocket()
  455. self.retryTime = None # next time, no delay before trying
  456. except socket.error:
  457. #Creation failed, so set the retry time and return.
  458. if self.retryTime is None:
  459. self.retryPeriod = self.retryStart
  460. else:
  461. self.retryPeriod = self.retryPeriod * self.retryFactor
  462. if self.retryPeriod > self.retryMax:
  463. self.retryPeriod = self.retryMax
  464. self.retryTime = now + self.retryPeriod
  465. def send(self, s):
  466. """
  467. Send a pickled string to the socket.
  468. This function allows for partial sends which can happen when the
  469. network is busy.
  470. """
  471. if self.sock is None:
  472. self.createSocket()
  473. #self.sock can be None either because we haven't reached the retry
  474. #time yet, or because we have reached the retry time and retried,
  475. #but are still unable to connect.
  476. if self.sock:
  477. try:
  478. if hasattr(self.sock, "sendall"):
  479. self.sock.sendall(s)
  480. else:
  481. sentsofar = 0
  482. left = len(s)
  483. while left > 0:
  484. sent = self.sock.send(s[sentsofar:])
  485. sentsofar = sentsofar + sent
  486. left = left - sent
  487. except socket.error:
  488. self.sock.close()
  489. self.sock = None # so we can call createSocket next time
  490. def makePickle(self, record):
  491. """
  492. Pickles the record in binary format with a length prefix, and
  493. returns it ready for transmission across the socket.
  494. """
  495. ei = record.exc_info
  496. if ei:
  497. # just to get traceback text into record.exc_text ...
  498. dummy = self.format(record)
  499. record.exc_info = None # to avoid Unpickleable error
  500. # See issue #14436: If msg or args are objects, they may not be
  501. # available on the receiving end. So we convert the msg % args
  502. # to a string, save it as msg and zap the args.
  503. d = dict(record.__dict__)
  504. d['msg'] = record.getMessage()
  505. d['args'] = None
  506. s = cPickle.dumps(d, 1)
  507. if ei:
  508. record.exc_info = ei # for next handler
  509. slen = struct.pack(">L", len(s))
  510. return slen + s
  511. def handleError(self, record):
  512. """
  513. Handle an error during logging.
  514. An error has occurred during logging. Most likely cause -
  515. connection lost. Close the socket so that we can retry on the
  516. next event.
  517. """
  518. if self.closeOnError and self.sock:
  519. self.sock.close()
  520. self.sock = None #try to reconnect next time
  521. else:
  522. logging.Handler.handleError(self, record)
  523. def emit(self, record):
  524. """
  525. Emit a record.
  526. Pickles the record and writes it to the socket in binary format.
  527. If there is an error with the socket, silently drop the packet.
  528. If there was a problem with the socket, re-establishes the
  529. socket.
  530. """
  531. try:
  532. s = self.makePickle(record)
  533. self.send(s)
  534. except (KeyboardInterrupt, SystemExit):
  535. raise
  536. except:
  537. self.handleError(record)
  538. def close(self):
  539. """
  540. Closes the socket.
  541. """
  542. self.acquire()
  543. try:
  544. sock = self.sock
  545. if sock:
  546. self.sock = None
  547. sock.close()
  548. finally:
  549. self.release()
  550. logging.Handler.close(self)
  551. class DatagramHandler(SocketHandler):
  552. """
  553. A handler class which writes logging records, in pickle format, to
  554. a datagram socket. The pickle which is sent is that of the LogRecord's
  555. attribute dictionary (__dict__), so that the receiver does not need to
  556. have the logging module installed in order to process the logging event.
  557. To unpickle the record at the receiving end into a LogRecord, use the
  558. makeLogRecord function.
  559. """
  560. def __init__(self, host, port):
  561. """
  562. Initializes the handler with a specific host address and port.
  563. """
  564. SocketHandler.__init__(self, host, port)
  565. self.closeOnError = 0
  566. def makeSocket(self):
  567. """
  568. The factory method of SocketHandler is here overridden to create
  569. a UDP socket (SOCK_DGRAM).
  570. """
  571. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  572. return s
  573. def send(self, s):
  574. """
  575. Send a pickled string to a socket.
  576. This function no longer allows for partial sends which can happen
  577. when the network is busy - UDP does not guarantee delivery and
  578. can deliver packets out of sequence.
  579. """
  580. if self.sock is None:
  581. self.createSocket()
  582. self.sock.sendto(s, (self.host, self.port))
  583. class SysLogHandler(logging.Handler):
  584. """
  585. A handler class which sends formatted logging records to a syslog
  586. server. Based on Sam Rushing's syslog module:
  587. http://www.nightmare.com/squirl/python-ext/misc/syslog.py
  588. Contributed by Nicolas Untz (after which minor refactoring changes
  589. have been made).
  590. """
  591. # from <linux/sys/syslog.h>:
  592. # ======================================================================
  593. # priorities/facilities are encoded into a single 32-bit quantity, where
  594. # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
  595. # facility (0-big number). Both the priorities and the facilities map
  596. # roughly one-to-one to strings in the syslogd(8) source code. This
  597. # mapping is included in this file.
  598. #
  599. # priorities (these are ordered)
  600. LOG_EMERG = 0 # system is unusable
  601. LOG_ALERT = 1 # action must be taken immediately
  602. LOG_CRIT = 2 # critical conditions
  603. LOG_ERR = 3 # error conditions
  604. LOG_WARNING = 4 # warning conditions
  605. LOG_NOTICE = 5 # normal but significant condition
  606. LOG_INFO = 6 # informational
  607. LOG_DEBUG = 7 # debug-level messages
  608. # facility codes
  609. LOG_KERN = 0 # kernel messages
  610. LOG_USER = 1 # random user-level messages
  611. LOG_MAIL = 2 # mail system
  612. LOG_DAEMON = 3 # system daemons
  613. LOG_AUTH = 4 # security/authorization messages
  614. LOG_SYSLOG = 5 # messages generated internally by syslogd
  615. LOG_LPR = 6 # line printer subsystem
  616. LOG_NEWS = 7 # network news subsystem
  617. LOG_UUCP = 8 # UUCP subsystem
  618. LOG_CRON = 9 # clock daemon
  619. LOG_AUTHPRIV = 10 # security/authorization messages (private)
  620. LOG_FTP = 11 # FTP daemon
  621. # other codes through 15 reserved for system use
  622. LOG_LOCAL0 = 16 # reserved for local use
  623. LOG_LOCAL1 = 17 # reserved for local use
  624. LOG_LOCAL2 = 18 # reserved for local use
  625. LOG_LOCAL3 = 19 # reserved for local use
  626. LOG_LOCAL4 = 20 # reserved for local use
  627. LOG_LOCAL5 = 21 # reserved for local use
  628. LOG_LOCAL6 = 22 # reserved for local use
  629. LOG_LOCAL7 = 23 # reserved for local use
  630. priority_names = {
  631. "alert": LOG_ALERT,
  632. "crit": LOG_CRIT,
  633. "critical": LOG_CRIT,
  634. "debug": LOG_DEBUG,
  635. "emerg": LOG_EMERG,
  636. "err": LOG_ERR,
  637. "error": LOG_ERR, # DEPRECATED
  638. "info": LOG_INFO,
  639. "notice": LOG_NOTICE,
  640. "panic": LOG_EMERG, # DEPRECATED
  641. "warn": LOG_WARNING, # DEPRECATED
  642. "warning": LOG_WARNING,
  643. }
  644. facility_names = {
  645. "auth": LOG_AUTH,
  646. "authpriv": LOG_AUTHPRIV,
  647. "cron": LOG_CRON,
  648. "daemon": LOG_DAEMON,
  649. "ftp": LOG_FTP,
  650. "kern": LOG_KERN,
  651. "lpr": LOG_LPR,
  652. "mail": LOG_MAIL,
  653. "news": LOG_NEWS,
  654. "security": LOG_AUTH, # DEPRECATED
  655. "syslog": LOG_SYSLOG,
  656. "user": LOG_USER,
  657. "uucp": LOG_UUCP,
  658. "local0": LOG_LOCAL0,
  659. "local1": LOG_LOCAL1,
  660. "local2": LOG_LOCAL2,
  661. "local3": LOG_LOCAL3,
  662. "local4": LOG_LOCAL4,
  663. "local5": LOG_LOCAL5,
  664. "local6": LOG_LOCAL6,
  665. "local7": LOG_LOCAL7,
  666. }
  667. #The map below appears to be trivially lowercasing the key. However,
  668. #there's more to it than meets the eye - in some locales, lowercasing
  669. #gives unexpected results. See SF #1524081: in the Turkish locale,
  670. #"INFO".lower() != "info"
  671. priority_map = {
  672. "DEBUG" : "debug",
  673. "INFO" : "info",
  674. "WARNING" : "warning",
  675. "ERROR" : "error",
  676. "CRITICAL" : "critical"
  677. }
  678. def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
  679. facility=LOG_USER, socktype=None):
  680. """
  681. Initialize a handler.
  682. If address is specified as a string, a UNIX socket is used. To log to a
  683. local syslogd, "SysLogHandler(address="/dev/log")" can be used.
  684. If facility is not specified, LOG_USER is used. If socktype is
  685. specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
  686. socket type will be used. For Unix sockets, you can also specify a
  687. socktype of None, in which case socket.SOCK_DGRAM will be used, falling
  688. back to socket.SOCK_STREAM.
  689. """
  690. logging.Handler.__init__(self)
  691. self.address = address
  692. self.facility = facility
  693. self.socktype = socktype
  694. if isinstance(address, basestring):
  695. self.unixsocket = 1
  696. self._connect_unixsocket(address)
  697. else:
  698. self.unixsocket = 0
  699. if socktype is None:
  700. socktype = socket.SOCK_DGRAM
  701. self.socket = socket.socket(socket.AF_INET, socktype)
  702. if socktype == socket.SOCK_STREAM:
  703. self.socket.connect(address)
  704. self.socktype = socktype
  705. self.formatter = None
  706. def _connect_unixsocket(self, address):
  707. use_socktype = self.socktype
  708. if use_socktype is None:
  709. use_socktype = socket.SOCK_DGRAM
  710. self.socket = socket.socket(socket.AF_UNIX, use_socktype)
  711. try:
  712. self.socket.connect(address)
  713. # it worked, so set self.socktype to the used type
  714. self.socktype = use_socktype
  715. except socket.error:
  716. self.socket.close()
  717. if self.socktype is not None:
  718. # user didn't specify falling back, so fail
  719. raise
  720. use_socktype = socket.SOCK_STREAM
  721. self.socket = socket.socket(socket.AF_UNIX, use_socktype)
  722. try:
  723. self.socket.connect(address)
  724. # it worked, so set self.socktype to the used type
  725. self.socktype = use_socktype
  726. except socket.error:
  727. self.socket.close()
  728. raise
  729. # curious: when talking to the unix-domain '/dev/log' socket, a
  730. # zero-terminator seems to be required. this string is placed
  731. # into a class variable so that it can be overridden if
  732. # necessary.
  733. log_format_string = '<%d>%s\000'
  734. def encodePriority(self, facility, priority):
  735. """
  736. Encode the facility and priority. You can pass in strings or
  737. integers - if strings are passed, the facility_names and
  738. priority_names mapping dictionaries are used to convert them to
  739. integers.
  740. """
  741. if isinstance(facility, basestring):
  742. facility = self.facility_names[facility]
  743. if isinstance(priority, basestring):
  744. priority = self.priority_names[priority]
  745. return (facility << 3) | priority
  746. def close (self):
  747. """
  748. Closes the socket.
  749. """
  750. self.acquire()
  751. try:
  752. if self.unixsocket:
  753. self.socket.close()
  754. finally:
  755. self.release()
  756. logging.Handler.close(self)
  757. def mapPriority(self, levelName):
  758. """
  759. Map a logging level name to a key in the priority_names map.
  760. This is useful in two scenarios: when custom levels are being
  761. used, and in the case where you can't do a straightforward
  762. mapping by lowercasing the logging level name because of locale-
  763. specific issues (see SF #1524081).
  764. """
  765. return self.priority_map.get(levelName, "warning")
  766. def emit(self, record):
  767. """
  768. Emit a record.
  769. The record is formatted, and then sent to the syslog server. If
  770. exception information is present, it is NOT sent to the server.
  771. """
  772. try:
  773. msg = self.format(record) + '\000'
  774. """
  775. We need to convert record level to lowercase, maybe this will
  776. change in the future.
  777. """
  778. prio = '<%d>' % self.encodePriority(self.facility,
  779. self.mapPriority(record.levelname))
  780. # Message is a string. Convert to bytes as required by RFC 5424
  781. if type(msg) is unicode:
  782. msg = msg.encode('utf-8')
  783. msg = prio + msg
  784. if self.unixsocket:
  785. try:
  786. self.socket.send(msg)
  787. except socket.error:
  788. self.socket.close() # See issue 17981
  789. self._connect_unixsocket(self.address)
  790. self.socket.send(msg)
  791. elif self.socktype == socket.SOCK_DGRAM:
  792. self.socket.sendto(msg, self.address)
  793. else:
  794. self.socket.sendall(msg)
  795. except (KeyboardInterrupt, SystemExit):
  796. raise
  797. except:
  798. self.handleError(record)
  799. class SMTPHandler(logging.Handler):
  800. """
  801. A handler class which sends an SMTP email for each logging event.
  802. """
  803. def __init__(self, mailhost, fromaddr, toaddrs, subject,
  804. credentials=None, secure=None):
  805. """
  806. Initialize the handler.
  807. Initialize the instance with the from and to addresses and subject
  808. line of the email. To specify a non-standard SMTP port, use the
  809. (host, port) tuple format for the mailhost argument. To specify
  810. authentication credentials, supply a (username, password) tuple
  811. for the credentials argument. To specify the use of a secure
  812. protocol (TLS), pass in a tuple for the secure argument. This will
  813. only be used when authentication credentials are supplied. The tuple
  814. will be either an empty tuple, or a single-value tuple with the name
  815. of a keyfile, or a 2-value tuple with the names of the keyfile and
  816. certificate file. (This tuple is passed to the `starttls` method).
  817. """
  818. logging.Handler.__init__(self)
  819. if isinstance(mailhost, (list, tuple)):
  820. self.mailhost, self.mailport = mailhost
  821. else:
  822. self.mailhost, self.mailport = mailhost, None
  823. if isinstance(credentials, (list, tuple)):
  824. self.username, self.password = credentials
  825. else:
  826. self.username = None
  827. self.fromaddr = fromaddr
  828. if isinstance(toaddrs, basestring):
  829. toaddrs = [toaddrs]
  830. self.toaddrs = toaddrs
  831. self.subject = subject
  832. self.secure = secure
  833. self._timeout = 5.0
  834. def getSubject(self, record):
  835. """
  836. Determine the subject for the email.
  837. If you want to specify a subject line which is record-dependent,
  838. override this method.
  839. """
  840. return self.subject
  841. def emit(self, record):
  842. """
  843. Emit a record.
  844. Format the record and send it to the specified addressees.
  845. """
  846. try:
  847. import smtplib
  848. from email.utils import formatdate
  849. port = self.mailport
  850. if not port:
  851. port = smtplib.SMTP_PORT
  852. smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout)
  853. msg = self.format(record)
  854. msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
  855. self.fromaddr,
  856. ",".join(self.toaddrs),
  857. self.getSubject(record),
  858. formatdate(), msg)
  859. if self.username:
  860. if self.secure is not None:
  861. smtp.ehlo()
  862. smtp.starttls(*self.secure)
  863. smtp.ehlo()
  864. smtp.login(self.username, self.password)
  865. smtp.sendmail(self.fromaddr, self.toaddrs, msg)
  866. smtp.quit()
  867. except (KeyboardInterrupt, SystemExit):
  868. raise
  869. except:
  870. self.handleError(record)
  871. class NTEventLogHandler(logging.Handler):
  872. """
  873. A handler class which sends events to the NT Event Log. Adds a
  874. registry entry for the specified application name. If no dllname is
  875. provided, win32service.pyd (which contains some basic message
  876. placeholders) is used. Note that use of these placeholders will make
  877. your event logs big, as the entire message source is held in the log.
  878. If you want slimmer logs, you have to pass in the name of your own DLL
  879. which contains the message definitions you want to use in the event log.
  880. """
  881. def __init__(self, appname, dllname=None, logtype="Application"):
  882. logging.Handler.__init__(self)
  883. try:
  884. import win32evtlogutil, win32evtlog
  885. self.appname = appname
  886. self._welu = win32evtlogutil
  887. if not dllname:
  888. dllname = os.path.split(self._welu.__file__)
  889. dllname = os.path.split(dllname[0])
  890. dllname = os.path.join(dllname[0], r'win32service.pyd')
  891. self.dllname = dllname
  892. self.logtype = logtype
  893. self._welu.AddSourceToRegistry(appname, dllname, logtype)
  894. self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
  895. self.typemap = {
  896. logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
  897. logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
  898. logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
  899. logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
  900. logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
  901. }
  902. except ImportError:
  903. print("The Python Win32 extensions for NT (service, event "\
  904. "logging) appear not to be available.")
  905. self._welu = None
  906. def getMessageID(self, record):
  907. """
  908. Return the message ID for the event record. If you are using your
  909. own messages, you could do this by having the msg passed to the
  910. logger being an ID rather than a formatting string. Then, in here,
  911. you could use a dictionary lookup to get the message ID. This
  912. version returns 1, which is the base message ID in win32service.pyd.
  913. """
  914. return 1
  915. def getEventCategory(self, record):
  916. """
  917. Return the event category for the record.
  918. Override this if you want to specify your own categories. This version
  919. returns 0.
  920. """
  921. return 0
  922. def getEventType(self, record):
  923. """
  924. Return the event type for the record.
  925. Override this if you want to specify your own types. This version does
  926. a mapping using the handler's typemap attribute, which is set up in
  927. __init__() to a dictionary which contains mappings for DEBUG, INFO,
  928. WARNING, ERROR and CRITICAL. If you are using your own levels you will
  929. either need to override this method or place a suitable dictionary in
  930. the handler's typemap attribute.
  931. """
  932. return self.typemap.get(record.levelno, self.deftype)
  933. def emit(self, record):
  934. """
  935. Emit a record.
  936. Determine the message ID, event category and event type. Then
  937. log the message in the NT event log.
  938. """
  939. if self._welu:
  940. try:
  941. id = self.getMessageID(record)
  942. cat = self.getEventCategory(record)
  943. type = self.getEventType(record)
  944. msg = self.format(record)
  945. self._welu.ReportEvent(self.appname, id, cat, type, [msg])
  946. except (KeyboardInterrupt, SystemExit):
  947. raise
  948. except:
  949. self.handleError(record)
  950. def close(self):
  951. """
  952. Clean up this handler.
  953. You can remove the application name from the registry as a
  954. source of event log entries. However, if you do this, you will
  955. not be able to see the events as you intended in the Event Log
  956. Viewer - it needs to be able to access the registry to get the
  957. DLL name.
  958. """
  959. #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
  960. logging.Handler.close(self)
  961. class HTTPHandler(logging.Handler):
  962. """
  963. A class which sends records to a Web server, using either GET or
  964. POST semantics.
  965. """
  966. def __init__(self, host, url, method="GET"):
  967. """
  968. Initialize the instance with the host, the request URL, and the method
  969. ("GET" or "POST")
  970. """
  971. logging.Handler.__init__(self)
  972. method = method.upper()
  973. if method not in ["GET", "POST"]:
  974. raise ValueError("method must be GET or POST")
  975. self.host = host
  976. self.url = url
  977. self.method = method
  978. def mapLogRecord(self, record):
  979. """
  980. Default implementation of mapping the log record into a dict
  981. that is sent as the CGI data. Overwrite in your class.
  982. Contributed by Franz Glasner.
  983. """
  984. return record.__dict__
  985. def emit(self, record):
  986. """
  987. Emit a record.
  988. Send the record to the Web server as a percent-encoded dictionary
  989. """
  990. try:
  991. import httplib, urllib
  992. host = self.host
  993. h = httplib.HTTP(host)
  994. url = self.url
  995. data = urllib.urlencode(self.mapLogRecord(record))
  996. if self.method == "GET":
  997. if (url.find('?') >= 0):
  998. sep = '&'
  999. else:
  1000. sep = '?'
  1001. url = url + "%c%s" % (sep, data)
  1002. h.putrequest(self.method, url)
  1003. # support multiple hosts on one IP address...
  1004. # need to strip optional :port from host, if present
  1005. i = host.find(":")
  1006. if i >= 0:
  1007. host = host[:i]
  1008. h.putheader("Host", host)
  1009. if self.method == "POST":
  1010. h.putheader("Content-type",
  1011. "application/x-www-form-urlencoded")
  1012. h.putheader("Content-length", str(len(data)))
  1013. h.endheaders(data if self.method == "POST" else None)
  1014. h.getreply() #can't do anything with the result
  1015. except (KeyboardInterrupt, SystemExit):
  1016. raise
  1017. except:
  1018. self.handleError(record)
  1019. class BufferingHandler(logging.Handler):
  1020. """
  1021. A handler class which buffers logging records in memory. Whenever each
  1022. record is added to the buffer, a check is made to see if the buffer should
  1023. be flushed. If it should, then flush() is expected to do what's needed.
  1024. """
  1025. def __init__(self, capacity):
  1026. """
  1027. Initialize the handler with the buffer size.
  1028. """
  1029. logging.Handler.__init__(self)
  1030. self.capacity = capacity
  1031. self.buffer = []
  1032. def shouldFlush(self, record):
  1033. """
  1034. Should the handler flush its buffer?
  1035. Returns true if the buffer is up to capacity. This method can be
  1036. overridden to implement custom flushing strategies.
  1037. """
  1038. return (len(self.buffer) >= self.capacity)
  1039. def emit(self, record):
  1040. """
  1041. Emit a record.
  1042. Append the record. If shouldFlush() tells us to, call flush() to process
  1043. the buffer.
  1044. """
  1045. self.buffer.append(record)
  1046. if self.shouldFlush(record):
  1047. self.flush()
  1048. def flush(self):
  1049. """
  1050. Override to implement custom flushing behaviour.
  1051. This version just zaps the buffer to empty.
  1052. """
  1053. self.acquire()
  1054. try:
  1055. self.buffer = []
  1056. finally:
  1057. self.release()
  1058. def close(self):
  1059. """
  1060. Close the handler.
  1061. This version just flushes and chains to the parent class' close().
  1062. """
  1063. try:
  1064. self.flush()
  1065. finally:
  1066. logging.Handler.close(self)
  1067. class MemoryHandler(BufferingHandler):
  1068. """
  1069. A handler class which buffers logging records in memory, periodically
  1070. flushing them to a target handler. Flushing occurs whenever the buffer
  1071. is full, or when an event of a certain severity or greater is seen.
  1072. """
  1073. def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
  1074. """
  1075. Initialize the handler with the buffer size, the level at which
  1076. flushing should occur and an optional target.
  1077. Note that without a target being set either here or via setTarget(),
  1078. a MemoryHandler is no use to anyone!
  1079. """
  1080. BufferingHandler.__init__(self, capacity)
  1081. self.flushLevel = flushLevel
  1082. self.target = target
  1083. def shouldFlush(self, record):
  1084. """
  1085. Check for buffer full or a record at the flushLevel or higher.
  1086. """
  1087. return (len(self.buffer) >= self.capacity) or \
  1088. (record.levelno >= self.flushLevel)
  1089. def setTarget(self, target):
  1090. """
  1091. Set the target handler for this handler.
  1092. """
  1093. self.target = target
  1094. def flush(self):
  1095. """
  1096. For a MemoryHandler, flushing means just sending the buffered
  1097. records to the target, if there is one. Override if you want
  1098. different behaviour.
  1099. """
  1100. self.acquire()
  1101. try:
  1102. if self.target:
  1103. for record in self.buffer:
  1104. self.target.handle(record)
  1105. self.buffer = []
  1106. finally:
  1107. self.release()
  1108. def close(self):
  1109. """
  1110. Flush, set the target to None and lose the buffer.
  1111. """
  1112. try:
  1113. self.flush()
  1114. finally:
  1115. self.acquire()
  1116. try:
  1117. self.target = None
  1118. BufferingHandler.close(self)
  1119. finally:
  1120. self.release()