代码之家  ›  专栏  ›  技术社区  ›  Sujoy

从SpringMVC控制器记录日志

  •  2
  • Sujoy  · 技术社区  · 16 年前

    我刚刚开始探索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());
        }
    }
    

    我有使用FixedWindowRollingPolicy登录文件的logback设置,配置为,

    <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方法。但什么也没发生。

    但是,当运行测试时,日志工作与预期一样,并且我在日志文件中有“返回索引视图”的特定条目。

    编辑: 目前在apache中使用tomcat6。

    logback配置文件logback.xml直接放在src(默认包)下。 正如我在部署后检查的那样,它被复制到WEB-INF/classes/

    2 回复  |  直到 16 年前
        1
  •  0
  •   Sujoy    16 年前

    听起来可能很奇怪,但当我使用appender.File属性的绝对路径时,我似乎很好地获得了日志!

    <File>/home/sujoy/logFile.log</File>
    

    举个例子,我得到了我所期望的日志。

    我不知道为什么会这样。特别是在测试日志时,日志工作正常。

        2
  •  0
  •   Mamad Purbo    16 年前