handlers.py 58 KB

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