0

I'm writing a Windows service in Python, using win32service, as described in the top answer of this question. It works.

However, as I write the code, anytime I make a mistake (say, a typo in a variable name), the only feedback I get is that the service dies.

Where can I see the regular python errors?

Edit: I should have stated that adding a TimedRotatingFileHandler is pretty much the only thing I've added so far - and yes, it works, but it's useless to catch typos or when forgetting to prefix variables names with "self.". I still have to experiment with catching the exceptions but even if I get that to work, in my mind, it's still a workaround, not a true solution.

jmr
  • 196
  • 1
  • 1
  • 10

3 Answers3

0

I'd suggest writing the program first, test it out, and then make it into a service. Otherwise you can try trapping errors and output that to a log file.

baldprussian
  • 164
  • 6
0

The best practice is to develop your service using an IDE like PyCharm, that way, it can find a lost of awkwardness (like typo) for you.

It is also really important to add a logging system, and log to a file. Your service is usually executed with a specific user with different privileges, so you must pay attention to the file access rights.

You can use AppDir Library to calculate the user log directory (see user_log_dir property.

Then, you can create a rotating log with a RotatingFileHandler.

In short:

logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.INFO)

# add a rotating handler
handler = RotatingFileHandler(path, maxBytes=1024**3,  # 1 Mo
                              backupCount=5)
logger.addHandler(handler)

Of course, this logger must be defined in your "main" function.

Your "main" function must have an exception handler. You need to catch all the exceptions (except KeyboardInterrupt and SystemExit) and log them.

To summarize:

def main():
    logger = init_logger()
    try:
        main_impl()
    except Exception as exc:
        logger.error("Last chance exception", exc_info=True)
        raise SystemExit(1)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • Not exactly what I was looking for, but accepted as the best answer for "exc_info=True", that fulfills 80% of my needs. Thanks. – jmr Sep 29 '17 at 22:21
0

That code uses pywin32. As such, in addition to the standard

python myservice.py install
python myservice.py start

there's also an

python myservice.py debug

It won't provide all errors either, but will provide valuable clues in many cases.

jmr
  • 196
  • 1
  • 1
  • 10