2022-05-26 01:23:30 +00:00
|
|
|
import logging.config
|
|
|
|
|
|
|
|
import structlog
|
|
|
|
|
|
|
|
|
2021-11-18 19:49:32 +00:00
|
|
|
# https://www.structlog.org/en/stable/standard-library.html
|
2022-06-01 00:34:22 +00:00
|
|
|
def setup_logging(filename: str = "", level: str = "DEBUG"):
|
2022-03-04 15:50:32 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
Args:
|
2022-05-09 00:41:49 +00:00
|
|
|
filename:
|
2022-06-01 00:34:22 +00:00
|
|
|
level:str: Log level to output, possible values are:
|
|
|
|
"CRITICAL", "FATAL", "ERROR", "WARNING", "WARN", "INFO", "DEBUG"
|
2022-03-04 15:50:32 +00:00
|
|
|
|
|
|
|
"""
|
2021-11-18 19:49:32 +00:00
|
|
|
|
2023-01-04 11:48:36 +00:00
|
|
|
timestamper = structlog.processors.TimeStamper(fmt="iso")
|
2021-11-18 19:49:32 +00:00
|
|
|
pre_chain = [
|
|
|
|
# Add the log level and a timestamp to the event_dict if the log entry
|
|
|
|
# is not from structlog.
|
|
|
|
structlog.stdlib.add_log_level,
|
|
|
|
timestamper,
|
|
|
|
]
|
|
|
|
|
2022-06-19 12:33:37 +00:00
|
|
|
config_dict = {
|
|
|
|
"version": 1,
|
|
|
|
"disable_existing_loggers": False,
|
|
|
|
"formatters": {
|
|
|
|
"plain": {
|
|
|
|
"()": structlog.stdlib.ProcessorFormatter,
|
|
|
|
"processor": structlog.dev.ConsoleRenderer(colors=False),
|
|
|
|
"foreign_pre_chain": pre_chain,
|
2021-11-18 19:49:32 +00:00
|
|
|
},
|
2022-06-19 12:33:37 +00:00
|
|
|
"colored": {
|
|
|
|
"()": structlog.stdlib.ProcessorFormatter,
|
|
|
|
"processor": structlog.dev.ConsoleRenderer(colors=True),
|
|
|
|
"foreign_pre_chain": pre_chain,
|
2021-11-18 19:49:32 +00:00
|
|
|
},
|
2022-06-19 12:33:37 +00:00
|
|
|
},
|
|
|
|
"handlers": {
|
|
|
|
"default": {
|
|
|
|
"level": level,
|
|
|
|
"class": "logging.StreamHandler",
|
|
|
|
"formatter": "colored",
|
2022-05-26 01:23:30 +00:00
|
|
|
},
|
2022-06-19 12:33:37 +00:00
|
|
|
},
|
|
|
|
"loggers": {
|
|
|
|
"": {
|
|
|
|
"handlers": ["default"],
|
|
|
|
"level": level,
|
|
|
|
"propagate": True,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
if filename:
|
|
|
|
config_dict["handlers"]["file"] = {
|
|
|
|
"level": level,
|
|
|
|
"class": "logging.handlers.WatchedFileHandler",
|
|
|
|
"filename": f"{filename}.log",
|
|
|
|
"formatter": "plain",
|
2022-05-26 01:23:30 +00:00
|
|
|
}
|
2022-06-19 12:33:37 +00:00
|
|
|
config_dict["loggers"][""]["handlers"].append("file")
|
|
|
|
|
|
|
|
logging.config.dictConfig(config_dict)
|
2021-11-18 19:49:32 +00:00
|
|
|
structlog.configure(
|
|
|
|
processors=[
|
|
|
|
structlog.stdlib.add_log_level,
|
|
|
|
structlog.stdlib.PositionalArgumentsFormatter(),
|
|
|
|
timestamper,
|
|
|
|
structlog.processors.StackInfoRenderer(),
|
|
|
|
structlog.processors.format_exc_info,
|
|
|
|
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
|
|
|
|
],
|
|
|
|
logger_factory=structlog.stdlib.LoggerFactory(),
|
|
|
|
wrapper_class=structlog.stdlib.BoundLogger,
|
|
|
|
cache_logger_on_first_use=True,
|
|
|
|
)
|