如何将Python BLE日志从终端重定向至文件或工作区?
Great question! Your existing pipe_logs_to_terminal function uses logging.StreamHandler to send logs to stdout. To route logs to a file or your workspace instead, you just need to swap that handler out for a logging.FileHandler and configure it properly. Here's how to adjust your code:
Modified Code for File Logging
import logging import sys def pipe_logs_to_file(self, log_file_path="bgapi_workspace_logs.log", level=logging.INFO): # Create a FileHandler that writes to your specified workspace file file_handler = logging.FileHandler(log_file_path) # Keep your original formatter (customize the string if needed) formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) api_logger = logging.getLogger("bgapi") # Add the file handler to the bgapi logger api_logger.addHandler(file_handler) api_logger.setLevel(level=level)
Key Changes Explained:
- Replace
StreamHandlerwithFileHandler: This handler writes logs directly to the file path you specify. Use an absolute path (like/your/workspace/path/bgapi_logs.log) to ensure it saves exactly where you want, or a relative path (which defaults to your script's working directory). - Customize the File Path: The default is
bgapi_workspace_logs.login your workspace, but you can pass any path when calling the function (e.g.,pipe_logs_to_file(self, "/home/user/projects/ble/logs/debug.log")). - Formatter Consistency: I kept your original log format so entries look identical to what you saw in the terminal—tweak the format string if you want to add/remove fields.
Want Both Terminal and File Logs?
If you still want to see logs in the terminal AND save them to a file, just add both handlers to the logger:
def pipe_logs_to_both(self, log_file_path="bgapi_workspace_logs.log", level=logging.INFO): # Terminal handler (original behavior) term_handler = logging.StreamHandler(sys.stdout) # File handler for workspace logging file_handler = logging.FileHandler(log_file_path) # Apply the same formatter to both formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s') term_handler.setFormatter(formatter) file_handler.setFormatter(formatter) api_logger = logging.getLogger("bgapi") api_logger.addHandler(term_handler) api_logger.addHandler(file_handler) api_logger.setLevel(level=level)
Bonus: Handle Large Log Files
If you expect logs to grow significantly, use RotatingFileHandler to automatically split logs into smaller files when they hit a size limit:
from logging.handlers import RotatingFileHandler def pipe_logs_to_rotating_file(self, log_file_path="bgapi_workspace_logs.log", max_size=10*1024*1024, backup_count=5, level=logging.INFO): # Rotate logs at 10MB, keep up to 5 backup log files file_handler = RotatingFileHandler( log_file_path, maxBytes=max_size, backupCount=backup_count ) formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) api_logger = logging.getLogger("bgapi") api_logger.addHandler(file_handler) api_logger.setLevel(level=level)
Just make sure your script has write permissions for the directory where you're saving the log file, and you're all set!
内容的提问来源于stack exchange,提问作者Sibelius

