Singleton Logger (logging)


/ Published in: Python
Save to your folder(s)

To use it, just change PATH and LOG_FILENAME in the source so that you save your .log file wherever you want.

Then just do:

foo = Logger("foo")

bar = Logger("bar")

foo.debug("debugging foo :D")

bar.info("informing bar :P")


Copy this code and paste it in your HTML
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2010 Rafa Muñoz Cárdenas
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. #
  8. # * Redistributions of source code must retain the above copyright notice,
  9. # this list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above copyright notice,
  11. # this list of conditions and the following disclaimer in the documentation
  12. # and/or other materials provided with the distribution.
  13. # * Neither the name of Pioneers of the Inevitable, Songbird, nor the names
  14. # of its contributors may be used to endorse or promote products derived
  15. # from this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  21. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  23. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  24. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  25. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. import os
  28. import logging
  29. import sys
  30.  
  31. PATH = os.path.join(os.path.expanduser("~"), ".folder")
  32. LOG_FILENAME = os.path.join(PATH, "program.log")
  33.  
  34. class Singleton(object):
  35. """
  36. Singleton interface:
  37. http://www.python.org/download/releases/2.2.3/descrintro/#__new__
  38. """
  39. def __new__(cls, *args, **kwds):
  40. it = cls.__dict__.get("__it__")
  41. if it is not None:
  42. return it
  43. cls.__it__ = it = object.__new__(cls)
  44. it.init(*args, **kwds)
  45. return it
  46.  
  47. def init(self, *args, **kwds):
  48. pass
  49.  
  50. class LoggerManager(Singleton):
  51. """
  52. Logger Manager.
  53. Handles all logging files.
  54. """
  55. def init(self):
  56. self.logger = logging.getLogger()
  57. handler = None
  58. if not os.path.isdir(PATH):
  59. try:
  60. os.mkdir(PATH) # create dir if it doesn't exist
  61. except:
  62. raise IOError("Couldn't create \"" + PATH + "\" folder. Check" \
  63. " permissions")
  64. try:
  65. handler = logging.FileHandler(LOG_FILENAME, "a")
  66. except:
  67. raise IOError("Couldn't create/open file \"" + \
  68. LOG_FILENAME + "\". Check permissions.")
  69. self.logger.setLevel(logging.DEBUG)
  70. formatter = logging.Formatter("%(asctime)s %(name)s - %(levelname)s - %(message)s")
  71. handler.setFormatter(formatter)
  72. self.logger.addHandler(handler)
  73.  
  74. def debug(self, loggername, msg):
  75. self.logger = logging.getLogger(loggername)
  76. self.logger.debug(msg)
  77.  
  78. def error(self, loggername, msg):
  79. self.logger = logging.getLogger(loggername)
  80. self.logger.error(msg)
  81.  
  82. def info(self, loggername, msg):
  83. self.logger = logging.getLogger(loggername)
  84. self.logger.info(msg)
  85.  
  86. def warning(self, loggername, msg):
  87. self.logger = logging.getLogger(loggername)
  88. self.logger.warning(msg)
  89.  
  90. class Logger(object):
  91. """
  92. Logger object.
  93. """
  94. def __init__(self, loggername="root"):
  95. self.lm = LoggerManager() # LoggerManager instance
  96. self.loggername = loggername # logger name
  97.  
  98. def debug(self, msg):
  99. self.lm.debug(self.loggername, msg)
  100.  
  101. def error(self, msg):
  102. self.lm.error(self.loggername, msg)
  103.  
  104. def info(self, msg):
  105. self.lm.info(self.loggername, msg)
  106.  
  107. def warning(self, msg):
  108. self.lm.warning(self.loggername, msg)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.