handlers.py 61 KB

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