logger.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import datetime
  2. import time
  3. import inspect
  4. import sys
  5. import os
  6. class Logger:
  7. CRITICAL, WARNING, INFO = range(3)
  8. levels = ['CRITICAL', 'WARNING', 'INFO']
  9. def write(self, level, line, nick=None, location=None):
  10. """
  11. Write out to the logfile of either default location or otherwise specified.
  12. Includes calling class in its logged line.
  13. Args:
  14. level: enumerated thing from the logger class.
  15. line: string. thing to write out to the logger.
  16. nick: string. determines filename.
  17. location: where to write the logfile out to.
  18. Returns:
  19. nothing.
  20. """
  21. if location is not None:
  22. l = location
  23. else:
  24. l = "~/"
  25. if nick is not None:
  26. n = nick
  27. else:
  28. n = 'pylog'
  29. try:
  30. if not os.path.exists(os.path.expanduser(l + '/logs/')):
  31. os.makedirs(os.path.expanduser(l + '/logs'))
  32. f = open(os.path.expanduser(l + '/logs/' + n + '-'+str(time.strftime("%m-%d-%Y")))+'.log', "a")
  33. f.write(str(datetime.datetime.now())+ " (" + inspect.stack()[1][3] + ") " + str(Logger.levels[level]) + ": " + line + '\n')
  34. except IOError:
  35. pass
  36. except OSError:
  37. print "probably permission denied."
  38. pass