Last active
November 21, 2020 17:15
-
-
Save scp93ch/cdb15468b84a8b3eb0aa to your computer and use it in GitHub Desktop.
Example simple Python service with logging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import logging | |
import logging.handlers | |
import argparse | |
import sys | |
import time # this is only being used as part of the example | |
# Deafults | |
LOG_FILENAME = "/tmp/myservice.log" | |
LOG_LEVEL = logging.INFO # Could be e.g. "DEBUG" or "WARNING" | |
# Define and parse command line arguments | |
parser = argparse.ArgumentParser(description="My simple Python service") | |
parser.add_argument("-l", "--log", help="file to write log to (default '" + LOG_FILENAME + "')") | |
# If the log file is specified on the command line then override the default | |
args = parser.parse_args() | |
if args.log: | |
LOG_FILENAME = args.log | |
# Configure logging to log to a file, making a new file at midnight and keeping the last 3 day's data | |
# Give the logger a unique name (good practice) | |
logger = logging.getLogger(__name__) | |
# Set the log level to LOG_LEVEL | |
logger.setLevel(LOG_LEVEL) | |
# Make a handler that writes to a file, making a new file at midnight and keeping 3 backups | |
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight", backupCount=3) | |
# Format each log message like this | |
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') | |
# Attach the formatter to the handler | |
handler.setFormatter(formatter) | |
# Attach the handler to the logger | |
logger.addHandler(handler) | |
# Make a class we can use to capture stdout and sterr in the log | |
class MyLogger(object): | |
def __init__(self, logger, level): | |
"""Needs a logger and a logger level.""" | |
self.logger = logger | |
self.level = level | |
def write(self, message): | |
# Only log if there is a message (not just a new line) | |
if message.rstrip() != "": | |
self.logger.log(self.level, message.rstrip()) | |
# Replace stdout with logging to file at INFO level | |
sys.stdout = MyLogger(logger, logging.INFO) | |
# Replace stderr with logging to file at ERROR level | |
sys.stderr = MyLogger(logger, logging.ERROR) | |
i = 0 | |
# Loop forever, doing something useful hopefully: | |
while True: | |
logger.info("The counter is now " + str(i)) | |
print "This is a print" | |
i += 1 | |
time.sleep(5) | |
if i == 3: | |
j = 1/0 # cause an exception to be thrown and the program to exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
very cool !!
just one thing please can you explain me, how i can talk (interact) with python program, when the prgram run inbackgroud ?
exemple :
i lunch the myservice.sh start
now th service run, but i want interact whith the python program, like i don't know how that's works.
thanks