handlers.py 57 KB

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