logfile.py 10 KB

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