1.在pom.xml中引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency>
2.在src/main/resources/下创建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 log4j.appender.Console.encoding=UTF-8 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = E:/logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 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*
3创建controller控制器
import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fansir.mapper.UserMapper; import com.fansir.model.User; @Controller public class IndexController { private static Logger log=Logger.getLogger(IndexController.class); @RequestMapping("/index") public String Index() { log.info("log4j整合完毕!!!"); return"index"; } }
4.此时在控制台输入出的日志信息如果有中文乱码的话,可以在src/main/resources/下创建logback.xml(不要改名),添加以下内容:
<?xml version="1.0" encoding="UTF-8"?> <!-- 处理日志中文乱码的配置 --> <!-- spirng boot 默认使用logback,默认会读取resources文件夹下的名为logback.xml的文件 zhangyu 20180807--> <configuration debug="false"> <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 --> <property name="LOG_HOME" value="C:/loghome" /> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 --> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> <!-- <charset>UTF-8</charset> --> </encoder> </appender> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>
亲测中文乱码解决!