演示环境:SpringBoot 2.2.1.RELEASE、Slf4j简单日志门面、log4j
参考我的另外一篇博客:
链接: IDEA 创建SpringBoot多级Maven父子项目-swotXu.
spring-boot-starter
包,
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<version>2.2.1.RELEASEversion>
<exclusions>
<exclusion>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-loggingartifactId>
exclusion>
exclusions>
dependency>
注意:这里需要移除默认log配置,否者抛出以下异常:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/maven/maven-repository-3.5.3/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/maven/maven-repository-3.5.3/org/slf4j/slf4j-log4j12/1.7.29/slf4j-log4j12-1.7.29.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
log4j
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-log4jartifactId>
<version>1.3.8.RELEASEversion>
dependency>
lombok
,可使用@Slf4j
注解,全局log
对象<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.10version>
<optional>trueoptional>
dependency>
在项目resources
目录下创建文件log4j.properties
博主这里,将日志分级别输出到不同文件中
先定义日志附加器:
log4j.appender.file_debug=org.apache.log4j.RollingFileAppender
log4j.appender.file_debug.layout=org.apache.log4j.PatternLayout
log4j.appender.file_debug.MaxFileSize=80MB
log4j.appender.file_debug.MaxBackupIndex=10
log4j.appender.file_debug.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss} (%C:%L line)] %m%n
log4j.appender.file_debug.Threshold=DEBUG
log4j.appender.file_debug.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.file_debug.filter.F1.LevelMin=DEBUG
log4j.appender.file_debug.filter.F1.LevelMax=DEBUG
log4j.appender.file_debug.append=true
log4j.appender.file_debug.Encoding=UTF-8
log4j.appender.file_debug.File=logs/concurrency/debug/debug.log
log4j.appender.file_info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file_info.DatePattern='_'yyyy-MM-dd-a
log4j.appender.file_info.layout=org.apache.log4j.PatternLayout
log4j.appender.file_info.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss} (%C:%L line)] %m%n
log4j.appender.file_info.Threshold=INFO
log4j.appender.file_info.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.file_info.filter.F1.LevelMin=INFO
log4j.appender.file_info.filter.F1.LevelMax=INFO
log4j.appender.file_info.append=true
log4j.appender.file_info.Encoding=UTF-8
log4j.appender.file_info.File=logs/concurrency/info/info.log
log4j.appender.file_error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file_error.DatePattern='_'yyyy-MM-dd
log4j.appender.file_error.layout=org.apache.log4j.PatternLayout
log4j.appender.file_error.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss} (%C:%L line)] %m%n
log4j.appender.file_error.Threshold=ERROR
log4j.appender.file_error.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.file_error.filter.F1.LevelMin=ERROR
log4j.appender.file_error.filter.F1.LevelMax=ERROR
log4j.appender.file_error.append=true
log4j.appender.file_error.Encoding=UTF-8
log4j.appender.file_error.File=logs/concurrency/erro/error.log
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.Encoding=UTF-8
log4j.appender.stdout.layout.ConversionPattern=[%-5p][%d{HH:mm:ss} %c{1}:%L line] %m%n
最后,设置项目日志级别为 INFO,使用前面定义的四种附加器
log4j.rootCategory=INFO,file_debug,file_info,file_error,stdout
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LogTest {
public static void main(String[] args) {
log.debug("test debug!");
log.info("test info!");
log.error("test error!");
}
}
背景:修改日志配置文件,无法立即生效,需要重新项目。在生成环境下,当然不能随便重启项目,可使用下面这种方式进行设置
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.Enumeration;
@Slf4j
@Controller
@RequestMapping("/logger")
public class LoggerController {
/**
* 设置指定包的日志级别
* @param packageName 需要修改的包名
* @param logLevel 日志级别
* @return
*/
@ResponseBody
@RequestMapping(value = "/change", method = RequestMethod.GET, produces = "application/json")
public String change(String packageName, String logLevel) {
try {
Level level = Level.toLevel(logLevel);
Logger logger = LogManager.getLogger(packageName);
logger.setLevel(level);
} catch (Exception e) {
return "失败";
}
return "成功";
}
/**
* 修改全局日志级别
* @param logLevel
* @return
*/
@ResponseBody
@RequestMapping(value = "/changeRoot", method = RequestMethod.GET, produces = "application/json")
public String change(String logLevel) {
try {
Level level = Level.toLevel(logLevel);
LogManager.getRootLogger().setLevel(level);
} catch (Exception e) {
return "失败";
}
return "成功";
}
/**
* 查看现在包的日志级别
* @param request
* @param response
*/
@RequestMapping(value = "/packageLoggers", method = RequestMethod.GET)
public void index(HttpServletRequest request, HttpServletResponse response) {
StringBuilder sb = new StringBuilder();
try {
sb.append("");
Writer writer = response.getWriter();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
Enumeration logs = LogManager.getCurrentLoggers();
while (logs.hasMoreElements()) {
Logger logger = (Logger) logs.nextElement();
sb.append("");
sb.append(logger.getName()).append(",").append(logger.getEffectiveLevel());
sb.append("");
}
sb.append("");
writer.write(sb.toString());
writer.flush();
if(writer != null){
writer.close();
}
log.info("项目日志级别:{}", sb.toString());
} catch (Exception e) {
}
}
}
com.swotxu.webdemo.demo
日志级别为DEBUG
http://localhost:8080/logger/change?logLevel=DEBUG&packageName=com.swotxu.webdemo.demo2
DEBUG
http://localhost:8080/logger/changeRoot?logLevel=DEBUG
http://localhost:8080/logger/packageLoggers
大家如果有什么疑问,欢迎评论留言!别忘了收藏关注~