handlers.py 61 KB

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