spring boot 使用log4j,不是log4j2
博客专区 > philonic 的博客 > 博客详情
spring boot 使用log4j,不是log4j2
philonic 发表于3个月前
spring boot 使用log4j,不是log4j2
  • 发表于 3个月前
  • 阅读 10
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

摘要: 最新的spring-boot中spring-boot-starter-log4j不可用,让他变为可用

spring-boot高版本都不再支持log4j,而是支持log4j2,log4j2使用xml配置,log4j使用properties可以在properties中使用变量。

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

然后再配置log4j.xml,对于习惯用properties的人来说有点别扭,就想使用properties配置log4j。 下面就看看我是怎么做的吧。 本次使用的是最新的spring boot RELEASE版本,1.5.6.RELEASE

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
    <relativePath/>
</parent>

首先,大家都知道的,去掉自带的logging依赖:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
          <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
          </exclusion>
        </exclusions>
</dependency>

第二步,去掉配置的spring-boot-log4j所有依赖, spring boot 1.5.6.RELEASE版本只有spring-boot-log4j2,没有spring-boot-log4j,配置了也没用, 所以我是直接注掉下面这一段,

<!--
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
-->

去掉了spring-boot-start-logging,高版本spring-boot也没有log4j,那我们就自己加上,需要添加log4j和commons-logging包,没有commons-logging会报错如下:

"C:\Program Files (x86)\Java\jdk1.8.0_60\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.1.1\lib\idea_rt.jar=54804:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.1.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\rt.jar;D:\Users\ex-zhangyongduo001\IdeaProjects\qwe\target\classes;D:\repository\org\springframework\boot\spring-boot-starter\1.5.6.RELEASE\spring-boot-starter-1.5.6.RELEASE.jar;D:\repository\org\springframework\boot\spring-boot\1.5.6.RELEASE\spring-boot-1.5.6.RELEASE.jar;D:\repository\org\springframework\spring-context\4.3.10.RELEASE\spring-context-4.3.10.RELEASE.jar;D:\repository\org\springframework\boot\spring-boot-autoconfigure\1.5.6.RELEASE\spring-boot-autoconfigure-1.5.6.RELEASE.jar;D:\repository\org\springframework\spring-core\4.3.10.RELEASE\spring-core-4.3.10.RELEASE.jar;D:\repository\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;D:\repository\org\springframework\boot\spring-boot-starter-web\1.5.6.RELEASE\spring-boot-starter-web-1.5.6.RELEASE.jar;D:\repository\org\springframework\boot\spring-boot-starter-tomcat\1.5.6.RELEASE\spring-boot-starter-tomcat-1.5.6.RELEASE.jar;D:\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.16\tomcat-embed-core-8.5.16.jar;D:\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.16\tomcat-embed-el-8.5.16.jar;D:\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.16\tomcat-embed-websocket-8.5.16.jar;D:\repository\org\hibernate\hibernate-validator\5.3.5.Final\hibernate-validator-5.3.5.Final.jar;D:\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;D:\repository\org\jboss\logging\jboss-logging\3.3.1.Final\jboss-logging-3.3.1.Final.jar;D:\repository\com\fasterxml\classmate\1.3.3\classmate-1.3.3.jar;D:\repository\com\fasterxml\jackson\core\jackson-databind\2.8.9\jackson-databind-2.8.9.jar;D:\repository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;D:\repository\com\fasterxml\jackson\core\jackson-core\2.8.9\jackson-core-2.8.9.jar;D:\repository\org\springframework\spring-web\4.3.10.RELEASE\spring-web-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-aop\4.3.10.RELEASE\spring-aop-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-beans\4.3.10.RELEASE\spring-beans-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-webmvc\4.3.10.RELEASE\spring-webmvc-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-expression\4.3.10.RELEASE\spring-expression-4.3.10.RELEASE.jar;D:\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar" com.zhang.App
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
	at org.springframework.boot.SpringApplication.<clinit>(SpringApplication.java:179)
	at com.zhang.App.main(App.java:19)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 2 more

Process finished with exit code 1

看报错,很明显是缺少commons-logging,那我们就给加上

<dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
</dependency>

<dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
</dependency>

至此,项目依赖就做好了,接下来编码试一下吧。 首先,写一个加载log4j配置文件的类, 注:spring-boot 1.2.5 RELEASE @ConfigurationProperties是有locations的,高版本spring-boot没有这个变量了,我们可以直接配置value

@ComponentScan
@ConfigurationProperties("classpath:log4j.properties")
public class Log4jConfigure {
}

接下来,app启动和controller调用,先看application代码:

@SpringBootApplication
public class App
{
    private static Logger logger = Logger.getLogger(App.class);

    public static void main( String[] args )
    {
        logger.info("spring boot App is starting.......");
        SpringApplication.run(App.class,args);
        logger.info("spring boot App is running........");

    }
}

controller写法

@RestController
@RequestMapping("/a")
public class HelloController {

    private static Logger logger = Logger.getLogger(HelloController.class);
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        logger.info("/a/hello     response:Hello Spring Boot!");
        return  "Hello Spring Boot!";
    }
}

接下来,见证奇迹的时刻,启动,访问,日志如下

"C:\Program Files (x86)\Java\jdk1.8.0_60\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.1.1\lib\idea_rt.jar=64053:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.1.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_60\jre\lib\rt.jar;D:\Users\ex-zhangyongduo001\IdeaProjects\qwe\target\classes;D:\repository\org\springframework\boot\spring-boot-starter\1.5.6.RELEASE\spring-boot-starter-1.5.6.RELEASE.jar;D:\repository\org\springframework\boot\spring-boot\1.5.6.RELEASE\spring-boot-1.5.6.RELEASE.jar;D:\repository\org\springframework\spring-context\4.3.10.RELEASE\spring-context-4.3.10.RELEASE.jar;D:\repository\org\springframework\boot\spring-boot-autoconfigure\1.5.6.RELEASE\spring-boot-autoconfigure-1.5.6.RELEASE.jar;D:\repository\org\springframework\spring-core\4.3.10.RELEASE\spring-core-4.3.10.RELEASE.jar;D:\repository\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;D:\repository\org\springframework\boot\spring-boot-starter-web\1.5.6.RELEASE\spring-boot-starter-web-1.5.6.RELEASE.jar;D:\repository\org\springframework\boot\spring-boot-starter-tomcat\1.5.6.RELEASE\spring-boot-starter-tomcat-1.5.6.RELEASE.jar;D:\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.16\tomcat-embed-core-8.5.16.jar;D:\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.16\tomcat-embed-el-8.5.16.jar;D:\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.16\tomcat-embed-websocket-8.5.16.jar;D:\repository\org\hibernate\hibernate-validator\5.3.5.Final\hibernate-validator-5.3.5.Final.jar;D:\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;D:\repository\org\jboss\logging\jboss-logging\3.3.1.Final\jboss-logging-3.3.1.Final.jar;D:\repository\com\fasterxml\classmate\1.3.3\classmate-1.3.3.jar;D:\repository\com\fasterxml\jackson\core\jackson-databind\2.8.9\jackson-databind-2.8.9.jar;D:\repository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;D:\repository\com\fasterxml\jackson\core\jackson-core\2.8.9\jackson-core-2.8.9.jar;D:\repository\org\springframework\spring-web\4.3.10.RELEASE\spring-web-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-aop\4.3.10.RELEASE\spring-aop-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-beans\4.3.10.RELEASE\spring-beans-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-webmvc\4.3.10.RELEASE\spring-webmvc-4.3.10.RELEASE.jar;D:\repository\org\springframework\spring-expression\4.3.10.RELEASE\spring-expression-4.3.10.RELEASE.jar;D:\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar" com.zhang.App
2017-09-12 10:20:35,511  INFO App:19 - spring boot App is starting.......

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.6.RELEASE)

2017-09-12 10:20:36,419  INFO App:48 - Starting App on IBNJ-D0438 with PID 7832 (D:\Users\ex-zhangyongduo001\IdeaProjects\qwe\target\classes started by EX-ZHANGYONGDUO001 in D:\Users\ex-zhangyongduo001\IdeaProjects\qwe)
2017-09-12 10:20:36,420  INFO App:593 - No active profile set, falling back to default profiles: default
2017-09-12 10:20:36,591  INFO AnnotationConfigEmbeddedWebApplicationContext:583 - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@bc8ab5: startup date [Tue Sep 12 10:20:36 CST 2017]; root of context hierarchy
2017-09-12 10:20:38,310  INFO Version:30 - HV000001: Hibernate Validator 5.3.5.Final
2017-09-12 10:20:40,039  INFO TomcatEmbeddedServletContainer:89 - Tomcat initialized with port(s): 8089 (http)
九月 12, 2017 10:20:40 上午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
九月 12, 2017 10:20:40 上午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.16
九月 12, 2017 10:20:40 上午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring embedded WebApplicationContext
2017-09-12 10:20:40,300  INFO ContextLoader:276 - Root WebApplicationContext: initialization completed in 3711 ms
2017-09-12 10:20:40,687  INFO ServletRegistrationBean:190 - Mapping servlet: 'dispatcherServlet' to [/]
2017-09-12 10:20:40,693  INFO FilterRegistrationBean:258 - Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-12 10:20:40,694  INFO FilterRegistrationBean:258 - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-12 10:20:40,695  INFO FilterRegistrationBean:258 - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-12 10:20:40,697  INFO FilterRegistrationBean:258 - Mapping filter: 'requestContextFilter' to: [/*]
2017-09-12 10:20:41,226  INFO RequestMappingHandlerAdapter:534 - Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@bc8ab5: startup date [Tue Sep 12 10:20:36 CST 2017]; root of context hierarchy
2017-09-12 10:20:41,389  INFO RequestMappingHandlerMapping:543 - Mapped "{[/a/hello]}" onto public java.lang.String com.zhang.web.HelloController.hello()
2017-09-12 10:20:41,393  INFO RequestMappingHandlerMapping:543 - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-12 10:20:41,394  INFO RequestMappingHandlerMapping:543 - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-12 10:20:41,464  INFO SimpleUrlHandlerMapping:362 - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-12 10:20:41,465  INFO SimpleUrlHandlerMapping:362 - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-12 10:20:41,538  INFO SimpleUrlHandlerMapping:362 - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-12 10:20:41,802  INFO AnnotationMBeanExporter:431 - Registering beans for JMX exposure on startup
2017-09-12 10:20:41,898  INFO TomcatEmbeddedServletContainer:201 - Tomcat started on port(s): 8089 (http)
2017-09-12 10:20:41,904  INFO App:57 - Started App in 6.118 seconds (JVM running for 6.88)
2017-09-12 10:20:41,905  INFO App:21 - spring boot App is running........
九月 12, 2017 10:25:44 上午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-09-12 10:25:44,999  INFO DispatcherServlet:489 - FrameworkServlet 'dispatcherServlet': initialization started
2017-09-12 10:25:45,021  INFO DispatcherServlet:508 - FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
2017-09-12 10:25:45,054  INFO HelloController:19 - /a/hello     response:Hello Spring Boot!

最后,差点忘了,log4j.properties配置,如下

# LOG4J配置
log4j.rootCategory=INFO,stdout,file
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

# 日志输出到文件
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=${project.basedir}/log/springboot.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

歇一下, 配置文件除了能配置spring-boot项目本身的变量,也可以自定义,例如:

# LOG4J配置
log4j.rootCategory=${root.category}

在Application的main方法里面添加

        System.setProperty("root.category", QweConstant.ROOT_LOGGER);
        logger.info("spring boot App is starting.......");
        SpringApplication.run(App.class,args);
        logger.info("spring boot App is running........");

然后就可以了。

大家可以支持转发一下。

共有 人打赏支持
粉丝 5
博文 21
码字总数 70635
×
philonic
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: