Home  >  Article  >  Java  >  How to customize the configuration file path and log4j2.xml location when java starts

How to customize the configuration file path and log4j2.xml location when java starts

WBOY
WBOYforward
2023-05-04 17:55:072468browse

    java启动时自定义配置文件路径,自定义log4j2.xml位置

    启动时指定配置文件位置

    项目打成jar包后,配置文件会一起打包到jar包的classes下,这就是所说的classpath。比如spring boot 就是在jar\BOOT-INF\classes下

    然后在jar文件运行时,就会自动去jar文件内找配置文件,这对我们部署服务是不利的,通常都是将配置文件放在外面,方便修改配置内容。

    有一种说法:说配置文件加载顺序为(由高到低)

    • jar包同级目录下的config文件夹下配置

    • jar包同级目录下配置

    • classpath下config目录下配置

    • classpath下配置

    经验证

    application.properties   或者 application.yml 是上面的加载顺序,但是我在搭建spring boot 项目时 【jar包同级目录下的config文件夹下配置】优先级是 > 【classpath下配置】,但是 【jar包同级目录下配置】优先级并没有【classpath下配置】的高。。不知为何。不过把配置文件放到  jar包同级目录下的config文件夹是能够解决需求的。

    后来又发现一个问题

    外部log4j2.xml 加载不到,不管是放在jar同级目录,还是jar包同级目录下的config,都不起作用,每次启动都加在 jar包内的log4j2.xml ,查了很多资料都说不到点上。

    后面终于找到解决办法了,就是在启动jar文件的时候手动加载,如下(start.sh内容)

    name="my-web"
    pid=`ps -ef | grep ${name} | grep -v grep |awk '{print $2}'`
    if [ $pid ]; then
        echo  ${name}  is  running pid=$pid
        kill -9 $pid
    fi
    nohup  java -Xms100m -Xmx100m  -jar ../${name}-0.0.1-SNAPSHOT.jar --logging.config=../config/log4j2.xml > ../logs/${name}.log & tail -f ../logs/${name}.log

    就是加上 【--logging.config=config/log4j2.xml】 来制定加载的 log4j2.xml

    如果启动不了

    pom 可能没有加上依赖

    
    
        org.springframework.boot
        spring-boot-starter
        
            
                org.springframework.boot
                spring-boot-starter-logging
            
        
    
     
    
        org.springframework.boot
        spring-boot-starter-log4j2
    

    最后附上整个文件的目录结构

    my-web
    ----bin
        ----start.sh
        ----stop.sh
    ----config
        ----log4j2.xml
        ----application.yml
        ----application.properties
    ----logs
    ----my-web.jar

    java服务启动指定配置文件路径

    How to customize the configuration file path and log4j2.xml location when java starts

    The above is the detailed content of How to customize the configuration file path and log4j2.xml location when java starts. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete