为在 Spring 启动应用程序中很早运行的代码启用调试日志记录

时间:2021-06-11 16:07:38

标签: java spring spring-boot spring-logback spring-vault

我正在编写一个小型 Spring 启动应用程序,我想从 Hashi Corp Vault 读取一些属性,这些属性最终将在 Kubernetes 环境中运行。 我通过使用 spring.cloud.vault 库和使用多个 spring.config.import 语句从 Vault 读取各种秘密路径来做到这一点。

我的 application.yaml 中有以下内容

spring:
  cloud:
    vault:
      uri: http://vault.vault.svc.cluster.local:8200
      connection-timeout: 5000
      read-timeout: 15000
      authentication: kubernetes
      kubernetes:
        role: ${vault.role.name}
        kubernetes-path: kubernetes
        service-account-token-file: /var/run/secrets/kubernetes.io/serviceaccount/token
  config:
    import:
      - vault://${secrets.engine.path}/${path1}
      - vault://${secrets.engine.path}/${path1}/${subpath}

在出现问题的情况下,Spring Cloud Vault 库将无法静默检索秘密,并且相应的 PropertySource 将为空,这很好,在这种情况下是可取的。但是,我希望能够将失败原因写入日志,以便于调试。 org.springframework.vault.core.env.LeaseAwareVaultPropertySource 类中有合适的调试功能,可以写出我一直试图启用的加载错误:

private void loadProperties() {

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Requesting secrets from Vault at %s using %s", this.requestedSecret.getPath(),
                    this.requestedSecret.getMode()));
        }

        this.secretLeaseContainer.addLeaseListener(this.leaseListener);
        this.secretLeaseContainer.addErrorListener(this.leaseListener);
        this.secretLeaseContainer.addRequestedSecret(this.requestedSecret);

        Exception loadError = this.loadError;
        if (this.notFound || loadError != null) {

            String msg = String.format("Vault location [%s] not resolvable", this.requestedSecret.getPath());

            if (this.ignoreSecretNotFound) {
                if (logger.isInfoEnabled()) {
                    logger.info(String.format("%s: %s", msg, loadError != null ? loadError.getMessage() : "Not found"));
                }
            }
            else {
                if (loadError != null) {
                    throw new VaultPropertySourceNotFoundException(msg, loadError);
                }
                throw new VaultPropertySourceNotFoundException(msg);
            }
        }
    }

我遇到的大多数文章都建议可以通过 application.yaml 启用日志记录上下文,但在这种情况下这对我不起作用。然后我尝试在启动应用程序时将其设置为系统属性: -Dlogging.level.org.springframework.vault.core.env.LeaseAwareVaultPropertySource=DEBUG 甚至更宽并设置 -Dlogging.level.org.springframework=TRACE

经过一些调试后,我可以看到使用系统属性,记录器的级别设置正确,但没有写出日志语句。

我现在认为经过进一步调试,问题是因为s​​pring.config.imports在准备环境的时候在Spring应用程序启动的时候很早就处理了,然后才初始化LogbackLoggingSystem,意味着没有日志被写出来在此之前。

所以我的问题是我完全卡住了,有没有办法真正让 LeaseAwareVaultPropertySource 中的日志出现在日志中? 是否可以在应用程序启动之前配置 Spring boot 以设置日志记录系统,然后才完全准备好环境?或者相反,延迟处理这些导入的时间点,以便首先初始化日志记录系统?

0 个答案:

没有答案