Created
April 17, 2024 03:45
-
-
Save kaitosawada/ed1b7eeabc8333d1fb1da1805f07e5eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from typing import Literal, Optional | |
import structlog | |
from structlog_sentry import SentryProcessor | |
def create_logger( | |
mode: Literal["json", "console"], | |
instance_name: Optional[str] = None, | |
container_id: Optional[str] = None, | |
log_level: int = logging.INFO, | |
) -> structlog.stdlib.BoundLogger: | |
match mode: | |
case "json": | |
renderer: structlog.typing.Processor = structlog.processors.JSONRenderer() | |
case "console": | |
renderer = structlog.dev.ConsoleRenderer() | |
case _: | |
raise ValueError(f"Invalid mode: {mode}") | |
structlog.configure( | |
processors=[ | |
structlog.processors.add_log_level, | |
structlog.contextvars.merge_contextvars, | |
structlog.processors.StackInfoRenderer(), | |
structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S", utc=False), | |
SentryProcessor(event_level=logging.ERROR, tag_keys="__all__"), | |
structlog.processors.format_exc_info, | |
renderer, | |
], | |
wrapper_class=structlog.make_filtering_bound_logger(log_level), | |
context_class=dict, | |
logger_factory=structlog.PrintLoggerFactory(), | |
cache_logger_on_first_use=False, | |
) | |
my_logger = structlog.get_logger() | |
if container_id is not None: | |
my_logger = my_logger.bind(container_id=container_id) | |
if instance_name is not None: | |
my_logger = my_logger.bind(instance_name=instance_name) | |
return my_logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
構造化ログのテンプレート
level
sentry
ERROR以上のログを自動的にsentryに送信します。
context
たとえばジョブIDなどのコンテキストを含めることができます。
コンテキストはバインドすることができます。一時的に同じコンテキストを含めたい場合に便利です。