structlog:显示Cloudwatch中的日志级别



我已经这样设置了我的日志记录器:

import logging
import structlog

class Logging:
@staticmethod
def my_logger() -> logging.Logger:
structlog.configure(
processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", key="ts"),
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)
logger = structlog.getLogger()
return logger

Cloudwatch中的事件现在看起来像这样:

2023-04-05T10:44:52.920+01:00   {"event": "My logging message", "level": "info", "ts": "2023-04-05T09:44:52.919867Z"}

相反,我想在一开始就看到日志级别,就像我在默认日志模块中看到的那样:

2023-04-05T10:44:52.920+01:00   [INFO] {"event": "My logging message", "level": "info", "ts": "2023-04-05T09:44:52.919867Z"}

我怎样才能做到这一点?

最简单的方法是在呈现的JSON之前加上方法名:

import logging
import structlog

def prepend_level(_, method: str, line: str) -> str:
return f"[{method.upper()}] {line}"

class Logging:
@staticmethod
def my_logger() -> logging.Logger:
structlog.configure(
processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", key="ts"),
structlog.processors.JSONRenderer(),
prepend_level,
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)
logger = structlog.getLogger()
return logger

Logging.my_logger().info("hey")

给我:

[INFO] {"event": "hey", "level": "info", "ts": "2023-04-05T12:19:33.803902Z"}

更简洁的版本正在包装json渲染器:

import logging
import structlog

class Logging:
@staticmethod
def my_logger() -> logging.Logger:
json_renderer = structlog.processors.JSONRenderer()
def render(logger, method, ed):
return f"[{ed['level'].upper()}] {json_renderer(logger, method, ed)}"
structlog.configure(
processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", key="ts"),
render,
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)
logger = structlog.getLogger()
return logger

Logging.my_logger().info("hey")

相关内容

  • 没有找到相关文章

最新更新