Log4j2配置

使用xml方式初始化Log4j2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="log.dir">D:/logs/demo</Property>
</Properties>
<Appenders>
<!-- 控制台appender -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger - %msg %ex %n"/>
</Console>
<RollingFile name="appFileLog" fileName="${log.dir}/app.log"
filePattern="${log.dir}/app-%d{yyyy-MM-dd}.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger - %msg %ex %n"/>
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<!-- 默认日志级别 debug -->
<Root level="debug">
<!-- 默认日志输出到 控制台 -->
<AppenderRef ref="Console"/>
<AppenderRef ref="appFileLog" />
</Root>
<!-- 打印spring info日志 -->
<logger name="org.springframework" level="info" />
</Loggers>
</Configuration>

使用java方式初始化Log4j2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package com.demo.utils.log;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.*;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.layout.PatternLayout;

import java.util.Map;

/**
* log4j2 工具类,提供java方式初始化log4j2,或者其他操作log4j2的方法
*/
public class Log4jHelper {

private static LoggerContext loggerContext = null;

public static final String DEFAULT_APPENDER = "STDOUT";

public static void resetSimpleRootLogger(String rootLoggerLevel) {
resetSimpleRootLogger(rootLoggerLevel, true);
}

/**
* 重置一个简化的rootLogger,将所有日志输出的控制台。当无法确定 log4j2 是否已经加载时,可用此方法。
*
* @param rootLoggerLevel rootLogger 日志级别
* @param isRemoveOldAppender 是否移除现有的appender
*/
public static void resetSimpleRootLogger(String rootLoggerLevel, boolean isRemoveOldAppender) {
loggerContext = (LoggerContext) LogManager.getContext(false);
Configuration config = loggerContext.getConfiguration();

ConsoleAppender.Builder builder = ConsoleAppender.newBuilder();
builder.withName(DEFAULT_APPENDER).withLayout(PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger - %msg %ex %n").build());
Appender stdoutAppender = builder.setTarget(ConsoleAppender.Target.SYSTEM_OUT).build();

config.addAppender(stdoutAppender);

LoggerConfig rootLoggerConfig = config.getRootLogger();
if (isRemoveOldAppender) {
Map<String, Appender> appenderMap = rootLoggerConfig.getAppenders();
if (!appenderMap.isEmpty()) {
for (String key : appenderMap.keySet()) {
rootLoggerConfig.removeAppender(key);
}
}
}
rootLoggerConfig.setLevel(Level.valueOf(rootLoggerLevel));
rootLoggerConfig.addAppender(stdoutAppender, Level.DEBUG, null);

loggerContext.updateLoggers();
}

/**
* 初始化Log4j2 ,需要确保该方法在所有日志操作前执行
*
* @param rootLoggerLevel 顶级logger 日志级别
*/
public static void init(String rootLoggerLevel) {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.WARN);
builder.setConfigurationName("Log4jHelper");
builder.add(
builder.newAppender(DEFAULT_APPENDER, "CONSOLE")
.addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT)
.add(
builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg %ex %n")
));
builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG)
.add(builder.newAppenderRef(DEFAULT_APPENDER)));

builder.add(builder.newRootLogger(Level.DEBUG).add(builder.newAppenderRef("STDOUT")));
loggerContext = Configurator.initialize(builder.build());
}

public static void init() {
init("DEBUG");
}

/**
* 向当前 log4j2 上下文中添加一个logger,该logger会被输出到控制台。
*
* @param name logger 名称
* @param level 日志级别
*/
public static void addLogger(String name, String level) {
addLogger(name, level, DEFAULT_APPENDER);
}

/**
* 向当前 log4j2 上下文中添加一个logger
*
* @param name logger 名称
* @param level 日志级别
* @param appenderName appenderName
*/
public static void addLogger(String name, String level, String appenderName) {
final Configuration config = loggerContext.getConfiguration();

Appender stdoutAppender = config.getAppender(appenderName);

LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, name, "false", new AppenderRef[]{}, new Property[]{}, config, null);
loggerConfig.addAppender(stdoutAppender, Level.valueOf(level), null);
loggerConfig.setLevel(Level.valueOf(level));
loggerConfig.setAdditive(false);

config.addLogger(name, loggerConfig);

loggerContext.updateLoggers();
}

/**
* 设置root日志级别
*
* @param loggerName
* @param level
*/
public static void setRootLevel(String level) {
Configuration config = loggerContext.getConfiguration();
LoggerConfig loggerConfig = config.getRootLogger();
loggerConfig.setLevel(Level.valueOf(level));
loggerContext.updateLoggers();
}

/**
* 设置日志级别
*
* @param loggerName
* @param level
*/
public static void setLevel(String loggerName, String level) {
Configuration config = loggerContext.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(loggerName);
loggerConfig.setLevel(Level.valueOf(level));
loggerContext.updateLoggers();
}

public static void main(String[] args) {

// Log4jHelper.resetSimpleRootLogger("debug");
Log4jHelper.init();
//
Log4jHelper.addLogger("accessLog", "info");
Logger accessLog = LogManager.getLogger("accessLog");
accessLog.debug("accessLog: debug");
accessLog.info("accessLog: info");
accessLog.error("accessLog: error");

Logger rootLogger = LogManager.getRootLogger();

rootLogger.debug("rootLogger: debug");
rootLogger.info("rootLogger: info");
rootLogger.error("rootLogger: error");

}

}

log4j2 java