无法使用log4j2写入日志

时间:2018-12-11 05:57:05

标签: java spring-boot tomcat logging log4j2

我正在使用spring boot使用log4j2.xml的以下配置来登录apache tomcat日志:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="60">
    <Properties>
        <Property name="logdir">${sys:catalina.base}/logs</Property>
        <Property name="layout">%d [%t] %-5p %c- %m%n</Property>
    </Properties>
    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="${layout}"/>
        </Console>
        <RollingFile name="FILEAPPENDER"
                     fileName="${logdir}/doc-reader.log"
                     filePattern="${logdir}/doc-reader.%d{yyyy-MM-dd}.log.gz">
            <PatternLayout pattern="${layout}"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="1 KB" />
            </Policies>
            <DefaultRolloverStrategy max="4"/>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="FILEAPPENDER"/>
        </Root>
        <Logger name="com.mypackage"
                level="info"
                additivity="false">
            <AppenderRef ref="FILEAPPENDER"/>
        </Logger>
    </Loggers>
</Configuration>

此配置能够在tomcat的logs /文件夹中创建日志和压缩日志。而且它还会写入系统生成的消息,例如:

2018-12-11 11:16:20,359 [http-nio-8089-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet- Completed initialization in 9 ms

但是当我尝试使用控制器进行日志记录时,它无法写入日志文件:

package com.mypackage.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author abhishekkeshri 07/12/2018
 */

@RestController
public class DevController {

    private static final Logger LOGGER = LogManager.getLogger(DevController.class);

    @RequestMapping(value = "/health")
    public String getCurrentDateTime() {

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        LOGGER.info("Info : number is " + dtf.format(now));
        LOGGER.warn("Warning : number is " + dtf.format(now));
        LOGGER.debug("Debug : number is " + dtf.format(now));
        LOGGER.error("Error : number is " + dtf.format(now));
        LOGGER.fatal("Fatal : number is " + dtf.format(now));
        return(dtf.format(now));
    }

}

我针对不同的Google搜索提出了各种解决方案,但均无济于事,因此考虑将其发布为问题。我在这里做什么错了?

我的项目结构是:

doc-reader > src > main > java > com.mypackage > controller > DevController
doc-reader > src > main > java > com.mypackage > startup > DRStartupCacheLoader

1 个答案:

答案 0 :(得分:0)

如果使用的是maven或gradle构建工具,则可以使用依赖项:

https://mvnrepository.com/artifact/org.slf4j/slf4j-api

添加此内容后,您可以尝试吗?

私有静态最终Logger LOGGER = LoggerFactory.getLogger(DevController.class);