我刚刚开始探索 SpringMVC 和 logback。
这是我的控制器,(到目前为止我只有一个)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class IndexController {
protected final static Logger logger = LoggerFactory.getLogger(IndexController.class);
@RequestMapping("/index")
public ModelAndView index() {
logger.info("Returning index view");
return new ModelAndView("index");
}
}
这是上面的测试代码。
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import org.springframework.web.servlet.ModelAndView;
public class IndexControllerTest {
@Test
public void index() throws Exception {
IndexController iController = new IndexController();
ModelAndView modelAndView = iController.index();
assertNotNull(modelAndView.getModel());
assertEquals("index", modelAndView.getViewName());
}
}
我有 logback 设置以使用 FixedWindowRollingPolicy 登录文件,配置是,
<configuration>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>logFile.log</File>
<RollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>logFile.%i.log</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>3</MaxIndex>
</RollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>5MB</MaxFileSize>
</triggeringPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%-26(%d{HH:mm:ss,SSS} [%thread]) %-5level %logger{32} - %msg%n
</Pattern>
</layout>
</appender>
<root level="info">
<appender-ref ref="FILE" />
</root>
</configuration>
我现在遇到的问题是,从浏览器访问站点时,日志文件中没有创建任何条目。我会假设控制器被调用,随后返回浏览器中显示的视图,因此应该在显示视图之前调用 log 方法。但什么也没有发生。
但是,在运行测试时,日志记录按预期工作,并且我在 logFile 中有“返回索引视图”的特定条目。
非常感谢有关上述情况的任何帮助或指导。
编辑: 目前使用带有 apache 的 tomcat6。
logback 配置文件 logback.xml 直接放在 src (默认包)下。正如我在部署后检查过的,它被复制到 WEB-INF/classes/