如何从Spring MVC登录

Luc*_*uke 3 java logging spring spring-mvc slf4j

我试图从Spring MVC中的控制器登录但没有出现.我正在使用SLF4J和logback.我设法从主类登录,但在将其作为Web应用程序后,它不会记录.

我认为它会起作用,因为SL4JF和Logback在类路径中.

@Controller
@RequestMapping(value = "/cars")
public class CarController {

    private Logger logger = LoggerFactory.getLogger(CarController.class);

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> newCar() {
        logger.info("new car");
        // more code
        return map;
    }
}
Run Code Online (Sandbox Code Playgroud)

logback.xml

<configuration scan="true">
    <property name="LOG_DIR" value="/My/User/Desktop"/>

    <!--Loggers-->
    <logger name="my.company" level="DEBUG"/>

    <!--Root logger-->
    <root level="debug">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE_ROLLER"/>
    </root>

    <!--Appenders-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE_ROLLER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/mylog.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>mylog.%d{yyyy-mm-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
</configuration>
Run Code Online (Sandbox Code Playgroud)

jel*_*ies 5

这是因为Spring默认使用Java Commons Logging.您应该将jcl-over-slf4j库放在类路径中,以便Spring使用SLF4J进行日志记录.

使用maven,除了SLF4J + Logback之外,还要使用这些依赖项:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${slf4j.version}</version>
    <scope>runtime</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :)