logger.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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, e:
  35. print "IO Error!"
  36. print e
  37. except OSError:
  38. print "probably permission denied."
  39. pass