springmvc java 输出json log4j 控制台输出日志

随着业务的扩展,有时需要输出日志方便找出系统中的bug。同时好的日志也可以迅速定位问题,加快开发速度

参考文献:

1、https://www.yiibai.com/log4j log4j教程

2、https://www.cnblogs.com/v-weiwang/p/4814050.html  springmvc+log4j 操作日志

依赖jar包

aopalliance-1.0.jar

commons-logging-1.2.jar

log4j-1.2.17.jar

spring-aop-4.3.8.RELEASE.jar

spring-beans-4.3.8.RELEASE.jar

spring-context-4.3.8.RELEASE.jar

spring-core-4.3.8.RELEASE.jar

spring-expression-4.3.8.RELEASE.jar

spring-web-4.3.8.RELEASE.jar

spring-webmvc-4.3.8.RELEASE.jar


操作步骤:

1、配置 web.xml 

serverJsonTest

springmvc

org.springframework.web.servlet.DispatcherServlet

    contextConfigLocation

    classpath:springmvc.xml

1

springmvc

*.do

    log4jConfigLocation

    /WEB-INF/log4j.properties

org.springframework.web.util.Log4jConfigListener

2、配置springmvc.xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

        http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context.xsd">

3、配置 log4j.properties

###设置###

log4j.rootLogger = debug,stdout,D,E

###输出信息到控制台##

log4j.appender.stdout = org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target = System.out

###格式化日志信息

log4j.appender.stdout.layout = org.apache.log4j.PatternLayout  

log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###

log4j.appender.E = org.apache.log4j.DailyRollingFileAppender

log4j.appender.E.File =E://logs/error.log

log4j.appender.E.Append = true

log4j.appender.E.Threshold = ERROR

log4j.appender.E.layout = org.apache.log4j.PatternLayout

log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

#close spring log out 

log4j.logger.org.springframework=WARN


4、在java 中调用log4j

package com.ccl.test.controller;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

//method=RequestMethod.GET get方法

//默认情况是 get+post

@RequestMapping(value="/app")

public class apiController {

private static Logger logger = Logger.getLogger(apiController.class);

@RequestMapping(value="/welcome.do")

//直接输出返回内容@ResponseBody

@ResponseBody

public String hello() {

//输出日志

logger.debug("hello");

//建立json串

StringBuffer sb = new StringBuffer();

sb.append("{\"word\":\"hello\"}");

String json = sb.toString();

return json;

}

}

最后输入网址 http://localhost:8080/工程名/app/welcome.do 查看输出内容

你可能感兴趣的:(springmvc java 输出json log4j 控制台输出日志)