logger.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/bin/env python
  2. #Copyright ReportLab Europe Ltd. 2000-2017
  3. #see license.txt for license details
  4. #history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/logger.py
  5. __version__='3.3.0'
  6. __doc__="Logging and warning framework, predating Python's logging package"
  7. from sys import stderr
  8. class Logger:
  9. '''
  10. An extended file type thing initially equivalent to sys.stderr
  11. You can add/remove file type things; it has a write method
  12. '''
  13. def __init__(self):
  14. self._fps = [stderr]
  15. self._fns = {}
  16. def add(self,fp):
  17. '''add the file/string fp to the destinations'''
  18. if isinstance(fp,str):
  19. if fp in self._fns: return
  20. fp = open(fn,'wb')
  21. self._fns[fn] = fp
  22. self._fps.append(fp)
  23. def remove(self,fp):
  24. '''remove the file/string fp from the destinations'''
  25. if isinstance(fp,str):
  26. if fp not in self._fns: return
  27. fn = fp
  28. fp = self._fns[fn]
  29. del self.fns[fn]
  30. if fp in self._fps:
  31. del self._fps[self._fps.index(fp)]
  32. def write(self,text):
  33. '''write text to all the destinations'''
  34. if text[-1]!='\n': text=text+'\n'
  35. for fp in self._fps: fp.write(text)
  36. def __call__(self,text):
  37. self.write(text)
  38. logger=Logger()
  39. class WarnOnce:
  40. def __init__(self,kind='Warn'):
  41. self.uttered = {}
  42. self.pfx = '%s: '%kind
  43. self.enabled = 1
  44. def once(self,warning):
  45. if warning not in self.uttered:
  46. if self.enabled: logger.write(self.pfx + warning)
  47. self.uttered[warning] = 1
  48. def __call__(self,warning):
  49. self.once(warning)
  50. warnOnce=WarnOnce()
  51. infoOnce=WarnOnce('Info')