handlers.py 59 KB

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