Oct-14-2023, 04:18 PM
I'm new to using classes. In the code below I'm finding with the use of
messages will appear once, as desired. However, when I use the class,
, 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.
1 |
log_alt.info() |
1 |
logger() |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
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) |