Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

logfile.py 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. # -*- test-case-name: twisted.test.test_logfile -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A rotating, browsable log file.
  6. """
  7. # System Imports
  8. import glob
  9. import os
  10. import stat
  11. import time
  12. from typing import BinaryIO, Optional, cast
  13. from twisted.python import threadable
  14. class BaseLogFile:
  15. """
  16. The base class for a log file that can be rotated.
  17. """
  18. synchronized = ["write", "rotate"]
  19. def __init__(
  20. self, name: str, directory: str, defaultMode: Optional[int] = None
  21. ) -> None:
  22. """
  23. Create a log file.
  24. @param name: name of the file
  25. @param directory: directory holding the file
  26. @param defaultMode: permissions used to create the file. Default to
  27. current permissions of the file if the file exists.
  28. """
  29. self.directory = directory
  30. self.name = name
  31. self.path = os.path.join(directory, name)
  32. if defaultMode is None and os.path.exists(self.path):
  33. self.defaultMode: Optional[int] = stat.S_IMODE(
  34. os.stat(self.path)[stat.ST_MODE]
  35. )
  36. else:
  37. self.defaultMode = defaultMode
  38. self._openFile()
  39. @classmethod
  40. def fromFullPath(cls, filename, *args, **kwargs):
  41. """
  42. Construct a log file from a full file path.
  43. """
  44. logPath = os.path.abspath(filename)
  45. return cls(os.path.basename(logPath), os.path.dirname(logPath), *args, **kwargs)
  46. def shouldRotate(self):
  47. """
  48. Override with a method to that returns true if the log
  49. should be rotated.
  50. """
  51. raise NotImplementedError
  52. def _openFile(self):
  53. """
  54. Open the log file.
  55. The log file is always opened in binary mode.
  56. """
  57. self.closed = False
  58. if os.path.exists(self.path):
  59. self._file = cast(BinaryIO, open(self.path, "rb+", 0))
  60. self._file.seek(0, 2)
  61. else:
  62. if self.defaultMode is not None:
  63. # Set the lowest permissions
  64. oldUmask = os.umask(0o777)
  65. try:
  66. self._file = cast(BinaryIO, open(self.path, "wb+", 0))
  67. finally:
  68. os.umask(oldUmask)
  69. else:
  70. self._file = cast(BinaryIO, open(self.path, "wb+", 0))
  71. if self.defaultMode is not None:
  72. try:
  73. os.chmod(self.path, self.defaultMode)
  74. except OSError:
  75. # Probably /dev/null or something?
  76. pass
  77. def write(self, data):
  78. """
  79. Write some data to the file.
  80. @param data: The data to write. Text will be encoded as UTF-8.
  81. @type data: L{bytes} or L{unicode}
  82. """
  83. if self.shouldRotate():
  84. self.flush()
  85. self.rotate()
  86. if isinstance(data, str):
  87. data = data.encode("utf8")
  88. self._file.write(data)
  89. def flush(self):
  90. """
  91. Flush the file.
  92. """
  93. self._file.flush()
  94. def close(self):
  95. """
  96. Close the file.
  97. The file cannot be used once it has been closed.
  98. """
  99. self.closed = True
  100. self._file.close()
  101. del self._file
  102. def reopen(self):
  103. """
  104. Reopen the log file. This is mainly useful if you use an external log
  105. rotation tool, which moves under your feet.
  106. Note that on Windows you probably need a specific API to rename the
  107. file, as it's not supported to simply use os.rename, for example.
  108. """
  109. self.close()
  110. self._openFile()
  111. def getCurrentLog(self):
  112. """
  113. Return a LogReader for the current log file.
  114. """
  115. return LogReader(self.path)
  116. class LogFile(BaseLogFile):
  117. """
  118. A log file that can be rotated.
  119. A rotateLength of None disables automatic log rotation.
  120. """
  121. def __init__(
  122. self,
  123. name,
  124. directory,
  125. rotateLength=1000000,
  126. defaultMode=None,
  127. maxRotatedFiles=None,
  128. ):
  129. """
  130. Create a log file rotating on length.
  131. @param name: file name.
  132. @type name: C{str}
  133. @param directory: path of the log file.
  134. @type directory: C{str}
  135. @param rotateLength: size of the log file where it rotates. Default to
  136. 1M.
  137. @type rotateLength: C{int}
  138. @param defaultMode: mode used to create the file.
  139. @type defaultMode: C{int}
  140. @param maxRotatedFiles: if not None, max number of log files the class
  141. creates. Warning: it removes all log files above this number.
  142. @type maxRotatedFiles: C{int}
  143. """
  144. BaseLogFile.__init__(self, name, directory, defaultMode)
  145. self.rotateLength = rotateLength
  146. self.maxRotatedFiles = maxRotatedFiles
  147. def _openFile(self):
  148. BaseLogFile._openFile(self)
  149. self.size = self._file.tell()
  150. def shouldRotate(self):
  151. """
  152. Rotate when the log file size is larger than rotateLength.
  153. """
  154. return self.rotateLength and self.size >= self.rotateLength
  155. def getLog(self, identifier):
  156. """
  157. Given an integer, return a LogReader for an old log file.
  158. """
  159. filename = "%s.%d" % (self.path, identifier)
  160. if not os.path.exists(filename):
  161. raise ValueError("no such logfile exists")
  162. return LogReader(filename)
  163. def write(self, data):
  164. """
  165. Write some data to the file.
  166. """
  167. BaseLogFile.write(self, data)
  168. self.size += len(data)
  169. def rotate(self):
  170. """
  171. Rotate the file and create a new one.
  172. If it's not possible to open new logfile, this will fail silently,
  173. and continue logging to old logfile.
  174. """
  175. if not (os.access(self.directory, os.W_OK) and os.access(self.path, os.W_OK)):
  176. return
  177. logs = self.listLogs()
  178. logs.reverse()
  179. for i in logs:
  180. if self.maxRotatedFiles is not None and i >= self.maxRotatedFiles:
  181. os.remove("%s.%d" % (self.path, i))
  182. else:
  183. os.rename("%s.%d" % (self.path, i), "%s.%d" % (self.path, i + 1))
  184. self._file.close()
  185. os.rename(self.path, "%s.1" % self.path)
  186. self._openFile()
  187. def listLogs(self):
  188. """
  189. Return sorted list of integers - the old logs' identifiers.
  190. """
  191. result = []
  192. for name in glob.glob("%s.*" % self.path):
  193. try:
  194. counter = int(name.split(".")[-1])
  195. if counter:
  196. result.append(counter)
  197. except ValueError:
  198. pass
  199. result.sort()
  200. return result
  201. def __getstate__(self):
  202. state = BaseLogFile.__getstate__(self)
  203. del state["size"]
  204. return state
  205. threadable.synchronize(LogFile)
  206. class DailyLogFile(BaseLogFile):
  207. """A log file that is rotated daily (at or after midnight localtime)"""
  208. def _openFile(self):
  209. BaseLogFile._openFile(self)
  210. self.lastDate = self.toDate(os.stat(self.path)[8])
  211. def shouldRotate(self):
  212. """Rotate when the date has changed since last write"""
  213. return self.toDate() > self.lastDate
  214. def toDate(self, *args):
  215. """Convert a unixtime to (year, month, day) localtime tuple,
  216. or return the current (year, month, day) localtime tuple.
  217. This function primarily exists so you may overload it with
  218. gmtime, or some cruft to make unit testing possible.
  219. """
  220. # primarily so this can be unit tested easily
  221. return time.localtime(*args)[:3]
  222. def suffix(self, tupledate):
  223. """Return the suffix given a (year, month, day) tuple or unixtime"""
  224. try:
  225. return "_".join(map(str, tupledate))
  226. except BaseException:
  227. # try taking a float unixtime
  228. return "_".join(map(str, self.toDate(tupledate)))
  229. def getLog(self, identifier):
  230. """Given a unix time, return a LogReader for an old log file."""
  231. if self.toDate(identifier) == self.lastDate:
  232. return self.getCurrentLog()
  233. filename = f"{self.path}.{self.suffix(identifier)}"
  234. if not os.path.exists(filename):
  235. raise ValueError("no such logfile exists")
  236. return LogReader(filename)
  237. def write(self, data):
  238. """Write some data to the log file"""
  239. BaseLogFile.write(self, data)
  240. # Guard against a corner case where time.time()
  241. # could potentially run backwards to yesterday.
  242. # Primarily due to network time.
  243. self.lastDate = max(self.lastDate, self.toDate())
  244. def rotate(self):
  245. """Rotate the file and create a new one.
  246. If it's not possible to open new logfile, this will fail silently,
  247. and continue logging to old logfile.
  248. """
  249. if not (os.access(self.directory, os.W_OK) and os.access(self.path, os.W_OK)):
  250. return
  251. newpath = f"{self.path}.{self.suffix(self.lastDate)}"
  252. if os.path.exists(newpath):
  253. return
  254. self._file.close()
  255. os.rename(self.path, newpath)
  256. self._openFile()
  257. def __getstate__(self):
  258. state = BaseLogFile.__getstate__(self)
  259. del state["lastDate"]
  260. return state
  261. threadable.synchronize(DailyLogFile)
  262. class LogReader:
  263. """Read from a log file."""
  264. def __init__(self, name):
  265. """
  266. Open the log file for reading.
  267. The comments about binary-mode for L{BaseLogFile._openFile} also apply
  268. here.
  269. """
  270. self._file = open(name) # Optional[BinaryIO]
  271. def readLines(self, lines=10):
  272. """Read a list of lines from the log file.
  273. This doesn't returns all of the files lines - call it multiple times.
  274. """
  275. result = []
  276. for i in range(lines):
  277. line = self._file.readline()
  278. if not line:
  279. break
  280. result.append(line)
  281. return result
  282. def close(self):
  283. self._file.close()