I wrote a relatively complex inventory script in python to automatically get the host list from the HTTP request response and query the local cache database and production database to classify it. I hope to output some logging system to this script, but I don’t know how to call the built-in logging system of ansible correctly.
I have set log_path in ansible.cfg and successfully output ansible logs. But it is difficult for this inventory script to output content to ansible logs.
I wrote a separate inventory script for testing. All its “logs” above the error level are output to one line, and the content at the info level is not output.
#!/usr/bin/env python3
import logging
import sys
logging.basicConfig(level=logging.INFO)
# Get the root logger
root_logger = logging.getLogger()
print(root_logger, file=sys.stderr)
# Output log level
logging.error("Log level: %s", logging.getLevelName(root_logger.getEffectiveLevel()))
# Output handler information
logging.error("Handlers:")
for handler in root_logger.handlers:
logging.error(f" - Type: {type(handler).__name__}")
if isinstance(handler, logging.FileHandler):
logging.error(f" - File path: {handler.baseFilename}")
if isinstance(handler, logging.StreamHandler):
logging.error(f" - Output stream: {handler.stream}")
logging.error(f" - Formatter: {handler.formatter}")
# Output formatter information
logging.error("Formatter:")
if root_logger.handlers:
formatter = root_logger.handlers[0].formatter
logging.error(f" - Format: {formatter._fmt}")
logging.error(f" - Date format: {formatter.datefmt}")
logging.debug("debug message\r\n")
logging.info("info message\r\n")
logging.warning("warning message\r\n")
logging.error("error message\r\n")
logging.critical("critical message\r\n")
print("print stderr message\r\n", file=sys.stderr)
# Outputs a blank host list.
print("{}")