Skip to content

Instantly share code, notes, and snippets.

@tongyx361
Last active November 30, 2023 13:30
Show Gist options
  • Save tongyx361/d1f06589dd399320d2c585e05c40767e to your computer and use it in GitHub Desktop.
Save tongyx361/d1f06589dd399320d2c585e05c40767e to your computer and use it in GitHub Desktop.
Initialize Logging in Python
def init_logging(
log_path=None,
format="[%(levelname)s] [%(asctime)s.%(msecs)d] [pid %(process)d] [%(pathname)s:%(lineno)d:%(funcName)s]\n%(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO,
force=True,
):
if force:
logging.shutdown()
# Setup logging
logging.basicConfig(
format=format,
datefmt=datefmt,
level=level,
force=force,
)
if log_path is not None:
file_handler = logging.FileHandler(log_path, mode="w") # 创建一个用于写入日志文件的 handler
file_handler.setLevel(logging.INFO) # 指定日志的最低输出级别
file_handler.setFormatter(
logging.Formatter(fmt=format, datefmt=datefmt)
) # 为 handler 指定输出格式
logging.getLogger().addHandler(file_handler) # 添加 handler 到 logger
logging.info(f"log_path = {log_path}")
init_logging(log_path=None)
logging.info("Test logging.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment