化石原创文章,转载请注明来源并保留原文链接


spring boot默认使用logback,所以要把默认的log先排除在外。

1、pom.xml中start_web库去除默认log

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2、resources下放置log4j2.xml,内容例子

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">c:/temp</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>

        <RollingFile name="appLog"
                     fileName="${APP_LOG_ROOT}/SpringBoot2App/application.log"
                     filePattern="${APP_LOG_ROOT}/SpringBoot2App/application-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB" />
            </Policies>
            <DefaultRolloverStrategy max="1" />
        </RollingFile>

    </Appenders>
    <Loggers>
        <Logger name="test" additivity="false">
            <AppenderRef ref="appLog" />
            <AppenderRef ref="Console" />
        </Logger>
        <Root level="debug">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

该配置会在控制台和硬盘上同时log出信息来。

3、在@SpringBootApplication的类里面初始化:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class MainApplicationClass extends SpringBootServletInitializer {
    private static final Logger LOGGER = LogManager.getLogger("test");

    public static void main(String[] args) {
        SpringApplication.run(MainApplicationClass.class, args);

        for (int i = 0; i < 1000; ++i) {
            LOGGER.info("A message for information.");
            LOGGER.debug("A message for debug.");
            LOGGER.error("A message for error.");
        }
    }
}

注意上面的getLogger的参数,必须对应到log4j2.xml中的logger的名字,如果控制台能出信息,文件能创造出来,但是信息在文件中却不存在,可能是该名字不匹配。


化石原创文章,转载请注明来源并保留原文链接



化石原创文章,转载请注明来源并保留原文链接


使用properties配置log4j2

1、配置文件(使用properties文件)

a) 放置log4j.properties到工程的根目录
b) 代码里指定该log4j.properties文件

String currentDirectory = System.getProperty("user.dir");
System.setProperty("log4j.configurationFile", currentDirectory + File.separator + "log4j.properties");

log4j.properties文件内容:

 status=warn
 name=properties_configuration
 #Give directory path where log files should get stored
 property.basePath=f:\/log\
 appenders=console, rolling
 #ConsoleAppender will print logs on console
 appender.console.type=Console
 appender.console.name=consoleLogger
 appender.console.target=SYSTEM_OUT
 appender.console.layout.type=PatternLayout
 #Specify the pattern of the logs
 appender.console.layout.pattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
 #RollingFileAppender will print logs in file which can be rotated based on time or size
 appender.rolling.type=RollingFile
 appender.rolling.name=fileLogger
 appender.rolling.fileName=${basePath}app.log
 appender.rolling.filePattern=${basePath}app_%d{yyyyMMdd}.log.gz
 appender.rolling.layout.type=PatternLayout
 appender.rolling.layout.pattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
 appender.rolling.policies.type=Policies
 #Rotate log file each day and keep 30 days worth
 appender.rolling.policies.time.type=TimeBasedTriggeringPolicy
 appender.rolling.policies.time.interval=1
 appender.rolling.policies.time.modulate=true
 appender.rolling.strategy.type=DefaultRolloverStrategy
 appender.rolling.strategy.delete.type=Delete
 appender.rolling.strategy.delete.basePath=${basePath}
 appender.rolling.strategy.delete.maxDepth=1
 appender.rolling.strategy.delete.ifLastModified.type=IfLastModified
 #Delete files older than 30 days
 appender.rolling.strategy.delete.ifLastModified.age=30d
 #Configure root logger for logging error logs in classes which are in package other than above specified package
 #level: ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
 rootLogger.level=all
 rootLogger.additivity=false
 rootLogger.appenderRef.rolling.ref=fileLogger
 rootLogger.appenderRef.console.ref=consoleLogger

2、代码得到logger句柄

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Logger logger = LogManager.getLogger(name);

3、具体使用

logger.debug(info);
logger.info(info);
logger.warn(info);
logger.error(info);
logger.trace(info);
logger.fatal(info);

使用上面的配置和方法,可以在文件(按上面log4j.properties的配置,在f:/log/app.log中)里和intellij的Console里输出debug、info、warn、error、trace、fatal信息。如果要控制输出的信息,可以在log4.properties文件的最后的部分改动:

rootLogger.level = xxx,比如 rootLogger.level = debug

注:

1、上面的例子代码中因为我们指定的代码是主程序的class的名字,在log4j.properties文件中找不到该名字的logger,所以log4j2会使用rootLogger这个默认的logger。

2、PatternLayout的手册在:

https://logging.apache.org/log4j/2.x/manual/layouts.html


化石原创文章,转载请注明来源并保留原文链接