|
| 1 | +import logging |
| 2 | +import sys |
| 3 | + |
| 4 | +import structlog |
| 5 | +from structlog.dev import ConsoleRenderer |
| 6 | +from structlog.processors import JSONRenderer |
| 7 | + |
| 8 | +from adf_core_python.core.agent.info.agent_info import AgentInfo |
| 9 | + |
| 10 | + |
| 11 | +def get_logger(name: str) -> structlog.BoundLogger: |
| 12 | + """ |
| 13 | + Get a logger with the given name. |
| 14 | + For kernel logging, use this function to get a logger. |
| 15 | +
|
| 16 | + Parameters |
| 17 | + ---------- |
| 18 | + name : str |
| 19 | + The name of the logger. |
| 20 | +
|
| 21 | + Returns |
| 22 | + ------- |
| 23 | + structlog.BoundLogger |
| 24 | + The logger with the given name. |
| 25 | + """ |
| 26 | + return structlog.get_logger(name) |
| 27 | + |
| 28 | + |
| 29 | +def get_agent_logger(name: str, agent_info: AgentInfo) -> structlog.BoundLogger: |
| 30 | + """ |
| 31 | + Get a logger with the given name and agent information. |
| 32 | + For agent logging, use this function to get a logger. |
| 33 | +
|
| 34 | + Parameters |
| 35 | + ---------- |
| 36 | + name : str |
| 37 | + The name of the logger. |
| 38 | + agent_info : AgentInfo |
| 39 | + The agent information. |
| 40 | +
|
| 41 | + Returns |
| 42 | + ------- |
| 43 | + structlog.BoundLogger |
| 44 | + The logger with the given name and agent information. |
| 45 | + """ |
| 46 | + return structlog.get_logger(name).bind( |
| 47 | + agent_id=str(agent_info.get_entity_id()), |
| 48 | + agent_type=str(agent_info.get_myself().get_urn().name), |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def configure_logger() -> None: |
| 53 | + structlog.configure( |
| 54 | + processors=[ |
| 55 | + structlog.stdlib.add_log_level, |
| 56 | + structlog.stdlib.add_logger_name, |
| 57 | + structlog.stdlib.PositionalArgumentsFormatter(), |
| 58 | + structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M.%S", utc=False), |
| 59 | + structlog.processors.StackInfoRenderer(), |
| 60 | + structlog.processors.UnicodeDecoder(), |
| 61 | + structlog.stdlib.ProcessorFormatter.wrap_for_formatter, |
| 62 | + ], |
| 63 | + logger_factory=structlog.stdlib.LoggerFactory(), |
| 64 | + wrapper_class=structlog.stdlib.BoundLogger, |
| 65 | + cache_logger_on_first_use=True, |
| 66 | + ) |
| 67 | + handler_stdout = logging.StreamHandler(sys.stdout) |
| 68 | + handler_stdout.setFormatter( |
| 69 | + structlog.stdlib.ProcessorFormatter(processor=ConsoleRenderer()) |
| 70 | + ) |
| 71 | + |
| 72 | + handler_file = logging.FileHandler("agent.log") |
| 73 | + handler_file.setFormatter( |
| 74 | + structlog.stdlib.ProcessorFormatter(processor=JSONRenderer()) |
| 75 | + ) |
| 76 | + |
| 77 | + root_logger = logging.getLogger() |
| 78 | + root_logger.addHandler(handler_stdout) |
| 79 | + root_logger.addHandler(handler_file) |
| 80 | + root_logger.setLevel(logging.DEBUG) |
0 commit comments