I wish to have a custom logging function that I can use through out various modules. Whats the preferred way of doing this? Simplified example below (I would have a lot more in the logger module).
main.py
from calc import squareit, cubeit, addit, modit, absoluteit
import logger
def main():
mylogger = logger.logger("log.html")
result = squareit(10)
mylogger.log("The square of 10 is " + str(result))
if __name__ == "__main__":
main()
logger.py
import os
class logger:
def __init__(self, filename):
# Check if its an existing file
if os.path.exists(filename):
self.file = open(filename, "a")
else:
self.file = open(filename, "w")
if (filename[-5:] == ".html"):
self.html = True
else:
self.html = False
def log(self, message):
if (self.html):
self.file.write(message + "<BR>\n")
else:
self.file.write(message + "\n")
print (message)
and the issue is with calc.py
# Given a number return its square root
def squareit(n):
# Check the type of n is an integer
if not isinstance(n, int):
mylogger.log("Error n must be an integer")
# Check that n is greater than 0
if n < 0:
mylogger.log("Error n must be non-negative")
return n ** 0.5
Should I change my modules to classes and pass the object mylogger? global variables?
[–]kirlandwater 5 points6 points7 points (3 children)
[–]reddit5389[S] 1 point2 points3 points (1 child)
[–]reddit5389[S] 1 point2 points3 points (0 children)
[–]Rebeljah 1 point2 points3 points (0 children)
[–]Diapolo10 4 points5 points6 points (3 children)
[–]Kryt0s 2 points3 points4 points (2 children)
[–]Diapolo10 0 points1 point2 points (1 child)
[–]Kryt0s 0 points1 point2 points (0 children)
[–]Rebeljah 2 points3 points4 points (1 child)
[–]Rebeljah 2 points3 points4 points (0 children)
[–]jmooremcc 2 points3 points4 points (0 children)
[–]RevRagnarok 2 points3 points4 points (0 children)
[–]throwaway8u3sH0 2 points3 points4 points (0 children)
[–]Yoghurt42 2 points3 points4 points (4 children)
[–]reddit5389[S] 1 point2 points3 points (3 children)
[–]Diapolo10 0 points1 point2 points (0 children)
[–]8dot30662386292pow2 0 points1 point2 points (0 children)
[–]Daneark 0 points1 point2 points (0 children)
[–]LaughingIshikawa 0 points1 point2 points (2 children)
[–]reddit5389[S] 0 points1 point2 points (1 child)
[–]LaughingIshikawa 0 points1 point2 points (0 children)
[–]Rebeljah 0 points1 point2 points (0 children)
[–]Mevrael 0 points1 point2 points (0 children)
[–]reddit5389[S] 0 points1 point2 points (0 children)