Oct-14-2023, 04:18 PM
I'm new to using classes. In the code below I'm finding with the use of
This code should function on any system with syslog available.
I understand I could just use logging outside of a class and get desired results, yet I'd like to better understand why the use of a class results in the duplicate messages.
log_alt.info()messages will appear once, as desired. However, when I use the class,
logger(), duplicate messages appear in syslog.
This code should function on any system with syslog available.
I understand I could just use logging outside of a class and get desired results, yet I'd like to better understand why the use of a class results in the duplicate messages.
import random, datetime, time, socket, logging, logging.handlers, threading, subprocess timer_one = 5 timer_two = 20 log_alt = logging.getLogger('logging_test') handler = logging.handlers.SysLogHandler(address = '/dev/log') formatter = logging.Formatter('%(name)s %(funcName)s(): %(message)s') handler.setFormatter(formatter) log_alt.addHandler(handler) log_alt.setLevel(logging.INFO) class logger: def __init__(self): self.l = logging.getLogger('logging_test') self.handler = logging.handlers.SysLogHandler(address = '/dev/log') self.formatter = logging.Formatter('%(name)s %(funcName)s(): %(message)s') self.handler.setFormatter(self.formatter) self.l.addHandler(self.handler) self.l.setLevel(logging.INFO) class showme: def __init__(self): pass def logsomething(self): logger().l.info(f'logging something...') # log_alt.info(f'logging something here...') class TimerThread(threading.Thread): def __init__(self, interval, function): threading.Thread.__init__(self) self.interval = interval self.function = function self.daemon = True def run(self): while True: logger().l.info(f'{str(self.function)} is sleeping for: {self.interval}') # log_alt.info(f'{str(self.function)} is sleeping for: {self.interval}') time.sleep(self.interval) self.function() if self.function == i.logsomething: self.interval = random.randint(7, 10) if __name__ == '__main__': logger().l.info(f'Starting this thing...') # log_alt.info(f'Starting this thing...') i = showme() timer1 = TimerThread(timer_one, i.logsomething) timer1.start() while True: time.sleep(timer_two)