handlers.py 61 KB

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