【问题标题】:How to pass gradle property of parent project to logback.xml in Spring Boot?如何在 Spring Boot 中将父项目的 gradle 属性传递给 logback.xml?
【发布时间】:2020-07-02 12:09:05
【问题描述】:

我有这个项目结构:

- parent-project
  - build.gradle
  - gradle.properties
  - child-project
    - build.gradle
    - src
      - main
        - java
        - resources
          - application.properties
          - logback.xml

这是父 build.gradle:

allprojects {
    apply plugin: 'java'
    apply plugin: 'groovy'
    apply plugin: 'maven'

    group = 'com.test'

    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11

    repositories {
        mavenLocal()
        maven {
            url nexusRepo
            credentials {
                username = nexusUsername
                password = nexusPassword
            }
        }
        mavenCentral()
        jcenter()
    }
    
    uploadArchives {
        repositories {
            mavenDeployer {
                repository(url: nexusRepo) {
                    authentication(userName: nexusUsername, password: nexusPassword)
                }
            }
        }
    }
}

uploadArchives.enabled = false

我的父项目的 gradle.properties 包含以下内容:

version=0.1.0-SNAPSHOT

这是子项目 build.gradle:

plugins {
    id 'org.springframework.boot' version '2.3.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
    id 'groovy'
    id 'war'
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

dependencies {
    //spring boot related dependencies
    ...
    implementation "com.xm.logback:jLogbackGelfAppender:1.1.0"
    implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.30'
    implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
    implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.2.3'
    implementation group: 'net.logstash.logback', name: 'logstash-logback-encoder', version: '6.3'
    ...
    //testing related dependencies
}

这是子项目application.properties:

prop.testserver.computer-name=${COMPUTERNAME}
...

# graylog properties
graylogHost=host.com
graylogPort=555
graylogSourceId=app_id_dev

我发布 prop.testserver.computer-name 属性的原因是因为我尝试使用 gradle resourceProcess 并收到有关此属性的错误。

这是我的 logback.xml:

<!DOCTYPE configuration>

<configuration>
  <contextName>${graylogSourceId}</contextName>
  <jmxConfigurator/>

  <springProperty scope="context" name="graylogHost" source="graylogHost"/>
  <springProperty scope="context" name="graylogPort" source="graylogPort"/>
  <springProperty scope="context" name="graylogSourceId" source="graylogSourceId"/>

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
  </appender>

  <appender name="GELF" class="com.xm.logback.GelfAppender">
    <server>${graylogHost}</server>
    <port>${graylogPort}</port>
    <protocol>TCP</protocol>
    <includeSource>true</includeSource>
    <includeMDC>true</includeMDC>
    <additionalFields>
      application=${graylogSourceId}
    </additionalFields>
    <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%m</pattern>
    </layout>
  </appender>

  <logger name="com.test" level="INFO">
    <appender-ref ref="GELF"/>
  </logger>

  <root level="INFO">
    <appender-ref ref="CONSOLE"/>
  </root>

</configuration>

我需要在 in logback 中添加一个 application_version,但我无法通过该过程尝试不同的版本。

首先我尝试使用此选项

  • application_version=${version},应用程序运行但记录器打印 version_IS_UNDEFINED
  • application_version=${project.version},应用程序运行但记录器打印 project.version_IS_UNDEFINED
  • application_version=@version@,应用程序运行但记录器打印@version@
  • application_version=@project.version@,应用程序运行但记录器打印@project.version@

然后我补充说:

processResources {
    filesMatching('application.properties') {
        expand(project.properties)
    }
}

到子项目 build.gradle 我得到了这个错误:

缺少用于 Groovy 模板扩展的属性 (COMPUTERNAME)。定义 键 [父、classLoaderScope、配置、插件、对象、 记录器,rootDir,projectRegistry,路径,testResultsDirName, targetCompatibility,java,规范化,bootJar,childProjects,jar, 状态,processResources,serviceRegistryFactory,任务,分机, projectDir,dependencyLocking,projectEvaluationBroadcaster, 依赖管理、项目路径、模块、继承范围、 nexusBuilder 用户名、版本、脚本、依赖项、 processTestResources,webAppDir,扩展,modelRegistry,安装, projectEvaluator,nexusBuilderUserPassword,projectConfigurator, archivesBaseName、日志记录、configurationActions、sourceCompatibility、 状态、子项目、组件、显示名称、bootWar、 nexusDeployerUsername、parentIdentifier、testClasses、 antBuilderFactory, out, standardOutputCapture, docsDir, compileTestGroovy、defaultTasks、nexusRepo、buildScriptSource、 autoTargetJvmDisabled、reportsDir、sonarqube、baseClassLoaderScope、 服务, assemble, gradle, distsDirName, buildFile, depth, 突变状态,docsDirName,testResultsDir,buildDir, scriptHandlerFactory,deferredProjectConfiguration,项目, conf2ScopeMappings、groovyRuntime、存储库、 nexusDeployerUserPassword、scriptPluginFactory、resourceLoader、 testReportDir, compileGroovy, mavenPomDir, group, artifacts, test, configurationTargetIdentifier, compileJava, check, webAppDirName, fileResolver、名称、testReportDirName、buildscript、springBoot、 processOperations, asDynamicObject, publicType, classes, identityPath, 描述、sourceSets、buildPath、fileOperations、pluginManager、 defaultArtifacts、类、modelSchemaStore、报告、约定、 allprojects,ant,war,resources,clean,compileTestJava,layout, 构建,侦听器BuildOperationDecorator,libsDir,distsDir, uploadArchives、rootProject、libsDirName、properties、providers]

我需要帮助以参数方式将应用程序版本从父 gradle.properties 传递到子项目 logback.xml。请帮忙,提前谢谢。

【问题讨论】:

    标签: java spring spring-boot gradle


    【解决方案1】:

    您当然可以在构建期间对您的属性文件执行搜索/替换。在您的情况下,它失败了,因为 Gradle 试图在您的 application.properties 文件中扩展 ${COMPUTERNAME} 引用。您可以通过使用filter 而不是expand 来解决它,或者通过将COMPUTERNAME 定义为值为“${COMPUTERNAME}”的Gradle 属性(本质上将值替换为自身)。 但是,为了在您的 logback 配置中包含应用程序版本,有一个(恕我直言)更优雅的解决方案。

    Spring Boot 在您的应用程序中有一个feature to include build information 作为属性文件。在 Gradle 中,您可以通过以下方式启用它:

    springBoot {
        buildInfo()
    }
    

    该文件将在META-INF/build-info.properties 下的运行时类路径中可用。然后,您可以将其作为属性源包含在 Logback 中:

    <configuration>
      <property resource="META-INF/build-info.properties" />
    </configuration>
    

    现在可以像之前对 Spring 属性所做的那样引用文件中的属性。尝试使用${build.version} 获取版本。

    您还可以让 Spring Boot 在启动信息消息中打印出版本。但是在这里你必须将它添加到 MANIFEST.MF 文件中,例如通过:

    bootJar {
      manifest {
        attributes(
          "Implementation-Title": project.name,
          "Implementation-Version": archiveVersion
        )
      }
    }
    

    (请注意,只有在您运行实际的 bootJar 文件时才会打印它 - 在 Gradle 中运行 bootRun 任务不会这样做。)

    【讨论】:

      【解决方案2】:

      这里有两个步骤

      1. 在 Build - 正在处理 application.properties
      2. 在运行时 - logback.xml 从 application.properties 初始化

      您只需在 application.properties 中添加项目版本
      my_version=${project.version}

      在 logback.xml 中使用 my_version

      还有 ${HOSTNAME} 而不是 ${COMPUTERMNAME}。 见http://logback.qos.ch/manual/configuration.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-11
        • 2017-02-10
        • 2023-03-29
        • 2015-03-18
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多