Search code examples
pythonloggingwindows-services

Error trying to log a windows service implementation in python


I am trying to build a windows service in Python and followed this article: http://thepythoncorner.com/dev/how-to-create-a-windows-service-in-python/


    import time
    import random
    from pathlib import Path
    from SMWinservice import SMWinservice
    
    import logging
    
    # Gets or creates a logger
    logger = logging.getLogger(__name__)
    
    # set log level
    logger.setLevel(logging.WARNING)
    
    # define file handler and set formatter
    file_handler = logging.FileHandler('LogsOrderIt.log')
    formatter    = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s (%(name)s)')
    file_handler.setFormatter(formatter) 
    
    # add file handler to logger
    logger.addHandler(file_handler)
    
    _svc_name_ = "OrderItService"
    _svc_display_name_ = "OrderIt Service"
    _svc_description_ = "Service intended to order my pdf files from Buffer"
    
    class OrderItService(SMWinservice):
    
        def start(self):
            self.isrunning = True
    
        def stop(self):
            self.isrunning = False
          
        def main(self):
            while self.isrunning:
                random.seed()
                x = random.randint(1, 1000000)
                Path(f"c:\df\{x}.txt").touch()
                logger.warning("New files named {path} created".format(a="c:\df\{x}.txt"))
                time.sleep(5)
    
    if __name__ == '__main__':
        OrderItService.parse_command_line()

In the code above, SMWinservice is the base class from the article without any change.

I wanted to add logs so I created a logger and try to start logging but i ended up with the following error:

The instance's SvcRun() method failed
<Error getting traceback - traceback.print_exception() failed
%2: %3

If I comment/remove the line below from my code it is working fine:


    logger.warning("New files named {path} created".format(a="c:\df\{x}.txt"))

I would appreciate if you could help me understand where my issue is coming from. Thanks


Solution

  • you could try to use f strings.

    are the "path" and "Path" suppose to be the same?

    Path(f"c:\df{x}.txt").touch() logger.warning("New files named {path} created".format(a="c:\df{x}.txt"))

    if so try this

    Path(f"c:\df{x}.txt").touch() logger.warning(f"New files named {Path} created")

    not so sure if this will solve anything but i just wondered