logger.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import datetime
  2. import inspect
  3. import os
  4. import sys
  5. import time
  6. class Logger:
  7. CRITICAL, WARNING, INFO = list(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. if sys.version_info > (3, 0, 0):
  34. f.write(str(datetime.datetime.now()) \
  35. + " (" + inspect.getframeinfo(inspect.stack()[1][0]).filename \
  36. + ":" + str(inspect.getframeinfo(inspect.stack()[1][0]).lineno) \
  37. + " <" + inspect.stack()[1][3] + ">) " + str(Logger.levels[level]) \
  38. + ": " + line + '\n')
  39. else:
  40. f.write(str(datetime.datetime.now())+ " (" + inspect.stack()[1][3] + ") " + str(Logger.levels[level]) + ": " + line + '\n')
  41. except IOError as e:
  42. print("IO Error!")
  43. print(e)
  44. except OSError:
  45. print("probably permission denied.")