naivelog.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. """
  2. Helper module to allow for simplified logging.
  3. Warning:
  4. In the future, this module may be removed. Its logic will
  5. be separated into some tracers and a SysLog logger.
  6. """
  7. import os
  8. import sys
  9. import datetime
  10. DEBUG, INFO, WARNING, ERROR, FATAL = 0, 1, 2, 3, 4
  11. """Level identifier."""
  12. def strToLevel(elvl):
  13. """
  14. Go from string identifier of a logging level to the
  15. level identifier.
  16. Args:
  17. elvl (str): Must be one of :code:`DEBUG`, :code:`INFO`,
  18. :code:`WARNING`, :code:`ERROR` or :code:`FATAL`,
  19. case-sensitive.
  20. See Also:
  21. - :func:`levelToStr`
  22. - :func:`levelToShortStr`
  23. """
  24. if elvl == "DEBUG":
  25. return DEBUG
  26. if elvl == "INFO":
  27. return INFO
  28. if elvl == "WARNING":
  29. return WARNING
  30. if elvl == "ERROR":
  31. return ERROR
  32. if elvl == "FATAL":
  33. return FATAL
  34. else:
  35. return None
  36. def levelToStr(lvl):
  37. """
  38. Go from a level identifier to the corresponding string representation.
  39. Args:
  40. lvl (int): The level identifier.
  41. See Also:
  42. - :func:`strToLevel`
  43. - :func:`levelToShortStr`
  44. """
  45. if lvl == DEBUG:
  46. return "DEBUG"
  47. if lvl == INFO:
  48. return "INFO"
  49. if lvl == WARNING:
  50. return "WARNING"
  51. if lvl == ERROR:
  52. return "ERROR"
  53. if lvl == FATAL:
  54. return "FATAL"
  55. return None
  56. def levelToShortStr(lvl):
  57. """
  58. Go from a level identifier to a short, representative string.
  59. Args:
  60. lvl (int): The level identifier.
  61. See Also:
  62. - :func:`strToLevel`
  63. - :func:`levelToStr`
  64. """
  65. if lvl == DEBUG:
  66. return "DBUG"
  67. if lvl == INFO:
  68. return "INFO"
  69. if lvl == WARNING:
  70. return "WARN"
  71. if lvl == ERROR:
  72. return "ERROR"
  73. if lvl == FATAL:
  74. return "FATAL"
  75. return None
  76. class Logger:
  77. """
  78. A simple logging class.
  79. Args:
  80. modulename (str): The name of the module.
  81. level (int): Lowest level for the logger to output.
  82. crashlevel (int): Level at which the logger should terminate.
  83. """
  84. def __init__(self, modulename, level, crashlevel):
  85. self.__modulename = modulename
  86. self.__level = level
  87. self.__crashlevel = crashlevel
  88. def debug(self, mainstr, *args, **kwargs):
  89. """
  90. Send :code:`DEBUG` message. Wrapper around the :func:`log` function.
  91. Args:
  92. mainstr (str): The main message information.
  93. *args: List of arguments for formatting the :code:`mainstr`.
  94. **kwargs: List of keyword arguments for formatting the
  95. :code:`mainstr`.
  96. """
  97. self.log(DEBUG, mainstr, *args, **kwargs)
  98. def info(self, mainstr, *args, **kwargs):
  99. """
  100. Send :code:`INFO` message. Wrapper around the :func:`log` function.
  101. Args:
  102. mainstr (str): The main message information.
  103. *args: List of arguments for formatting the :code:`mainstr`.
  104. **kwargs: List of keyword arguments for formatting the
  105. :code:`mainstr`.
  106. """
  107. self.log(INFO, mainstr, *args, **kwargs)
  108. def warning(self, mainstr, *args, **kwargs):
  109. """
  110. Send :code:`WARNING` message. Wrapper around the :func:`log` function.
  111. Args:
  112. mainstr (str): The main message information.
  113. *args: List of arguments for formatting the :code:`mainstr`.
  114. **kwargs: List of keyword arguments for formatting the
  115. :code:`mainstr`.
  116. """
  117. self.log(WARNING, mainstr, *args, **kwargs)
  118. def error(self, mainstr, *args, **kwargs):
  119. """
  120. Send :code:`ERROR` message. Wrapper around the :func:`log` function.
  121. Args:
  122. mainstr (str): The main message information.
  123. *args: List of arguments for formatting the :code:`mainstr`.
  124. **kwargs: List of keyword arguments for formatting the
  125. :code:`mainstr`.
  126. """
  127. self.log(ERROR, mainstr, *args, **kwargs)
  128. def fatal(self, mainstr, *args, **kwargs):
  129. """
  130. Send :code:`FATAL` message. Wrapper around the :func:`log` function.
  131. Args:
  132. mainstr (str): The main message information.
  133. *args: List of arguments for formatting the :code:`mainstr`.
  134. **kwargs: List of keyword arguments for formatting the
  135. :code:`mainstr`.
  136. """
  137. self.log(FATAL, mainstr, *args, **kwargs)
  138. def log(self, level, mainstr, *args, **kwargs):
  139. """
  140. Send a message.
  141. Args:
  142. level (int): Level at which there must be logged.
  143. mainstr (str): The main message information.
  144. *args: List of arguments for formatting the :code:`mainstr`.
  145. **kwargs: List of keyword arguments for formatting the
  146. :code:`mainstr`.
  147. See Also:
  148. - :func:`debug`
  149. - :func:`info`
  150. - :func:`warning`
  151. - :func:`error`
  152. - :func:`fatal`
  153. """
  154. if level >= self.__level:
  155. sys.stdout.write(self.formatmsg(level,str(mainstr).format(*args, **kwargs)))
  156. if level >= self.__crashlevel:
  157. exit(1)
  158. def setLevel(self, level):
  159. """
  160. Sets the level to a new value.
  161. Args:
  162. level (int): The new level.
  163. """
  164. self.__level = level
  165. def formatmsg(self, level, mainstr):
  166. """
  167. Formats the message, used internally.
  168. Args:
  169. level (int): The level of the message.
  170. mainstr (str): The main message to print.
  171. """
  172. class bcolors:
  173. """
  174. Helper class to set the colors to the terminal.
  175. """
  176. HEADER = '\033[95m'
  177. OKBLUE = '\033[94m'
  178. OKGREEN = '\033[92m'
  179. WARNING = '\033[93m'
  180. FAIL = '\033[91m'
  181. ENDC = '\033[0m'
  182. col = bcolors.OKGREEN
  183. if level >= WARNING:
  184. col = bcolors.WARNING
  185. if level >= ERROR:
  186. col = bcolors.FAIL
  187. return "{startcol}[{now:%H:%M:%S.%f} {module} {lvl}] {mainstr}{endcol}\n".format(
  188. lvl=levelToShortStr(level),
  189. module=self.__modulename,
  190. now=datetime.date.today(),
  191. mainstr=mainstr,
  192. startcol=col,
  193. endcol=bcolors.ENDC)
  194. defaultLogLevel = INFO
  195. """Default level at which logging is enabled."""
  196. defaultCrashLevel = FATAL
  197. """Default level at which a termination must occur."""
  198. def getAbstractLogLevel(env, default):
  199. """
  200. Obtains the log level from the environment variables.
  201. Args:
  202. env (str): Variable name.
  203. default (Any): The default value if the variable does not
  204. exist.
  205. """
  206. elvl = os.environ[env] if env in os.environ else ''
  207. lvl = strToLevel(elvl)
  208. if lvl:
  209. return lvl
  210. else:
  211. return default
  212. def getLogLevel():
  213. """
  214. Gets the logging level from the environment.
  215. """
  216. return getAbstractLogLevel('NAIVE_LOGLEVEL', defaultLogLevel)
  217. def getCrashLevel():
  218. """
  219. Gets the crash level from the environment.
  220. """
  221. return getAbstractLogLevel('NAIVE_CRASHLEVEL', defaultCrashLevel)
  222. def getLogger(modulename):
  223. """
  224. Gets the logger for a certain module.
  225. Args:
  226. modulename (str): The module's name.
  227. """
  228. return Logger(modulename, getLogLevel(), getCrashLevel())
  229. if __name__ == "__main__":
  230. l = getLogger('testmodule')
  231. l.info("bla")
  232. l.info("test nummer {}{}", 2, " is good")
  233. l.info("test {hier} is ook ok", hier=3, daar=4)
  234. l.info("should not see this")
  235. l2 = getLogger('testmodule.m2')
  236. l2.info("More info")
  237. l2.info("and even more")