0

I started tinkering with logging and BLE. Now I got this piece of code I took from the bgapi package. I think I kind of understand how it works, but I'd like to see the output in a file or in the workspace. How would I achieve this?

def pipe_logs_to_terminal(self, level=logging.INFO):
    term = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - 
    %(name)s - %(levelname)s - %(message)s')
    term.setFormatter(formatter)
    api_logger = logging.getLogger("bgapi")
    api_logger.addHandler(term)
    api_logger.setLevel(level=level)
1

1 Answer 1

0

You simply use logging.FileHandler(). I tried to implement it in your method:

def pipe_logs_to_terminal(self, level=logging.INFO):
    log_path = "."  # cwd
    file_name = "my_app"
    # configure root logger
    api_logger = logging.getLogger("bgapi")
    api_logger.setLevel(level=level)
    # set format
    formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s')
    # configure file handler
    file_handler = logging.FileHandler("{0}/{1}.log".format(log_path, file_name))
    file_handler.setFormatter(formatter)
    api_logger.addHandler(file_handler)
    # configure console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    api_logger.addHandler(console_handler)

Optionally you could omit the console_handler (called term in your example) part, if you choose to only pipe your logging into a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.