| 2017.8.31 | java |
1.需求场景:
在开发过程中,需要动态输出调试的内容,但是又不想在发布的时候输出调试的东西,就需要动态修改日志级别
一般情况下是使用配置文件来进行配置修改,也可以使用如下的代码方式进行修改
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DevLog {
private static final Logger logger = Logger.getLogger(DevLog.class.getName());
static {
Logger rootLogger = Logger.getLogger("");
for (Handler handler : rootLogger.getHandlers()) {
handler.setLevel(Level.FINE);
}
rootLogger.setLevel(Level.FINE);
}
public static void debug(String msg) {
logger.fine(msg);
}
public static void debug(String msg, Throwable thrown) {
logger.log(Level.FINE, msg, thrown);
}
public static void debug(String msg, Object[] params) {
logger.log(Level.FINE, msg, params);
}
public static void info(String msg) {
logger.info(msg);
}
public static void info(String msg, Throwable thrown) {
logger.log(Level.INFO, msg, thrown);
}
public static void info(String msg, Object[] params) {
logger.log(Level.INFO, msg, params);
}
public static void error(String msg) {
logger.severe(msg);
}
public static void error(String msg, Throwable thrown) {
logger.log(Level.SEVERE, msg, thrown);
}
public static void error(String msg, Object[] params) {
logger.log(Level.SEVERE, msg, params);
}
public static void main(String[] args) {
logger.finer("lower than fine, it won't be show");
logger.config("higher than fine, it will be show");
logger.severe("higher than fine, it will be show2");
}
}
2.由于项目的特殊性,并不需要动态修改的内容,只需要修改jre/lib/logging.properties中
.level= INFO为FINE
java.util.logging.ConsoleHandler.level = INFO为FINE
3.log4j中NDC、MDC和ThreadContext使用
NDC方式:
import java.io.FileReader;
import org.apache.Log4j.Logger;
import org.apache.Log4j.NDC;
...
String username = "admin";
String sessionID = "1234";
NDC.push(username);
NDC.push(sessionID);
try {
// tmpFile doesn't exist, causing an exception.
FileReader fr = new FileReader("tmpFile");
}
catch (Exception ex) {
logger.error("Unable to open file.");
}
finally {
NDC.pop();
NDC.pop();
NDC.remove();
}
“admin 1234 ERROR – Unable to open file.”
MDC方式:
import java.io.FileReader;
import org.apache.Log4j.Logger;
import org.apache.Log4j.MDC;
...
MDC.put("username", "admin");
MDC.put("sessionID", "1234");
try {
// tmpFile doesn't exist, causing an exception.
FileReader fr = new FileReader("tmpFile");
}
catch (Exception ex) {
logger.error("Unable to open file!");
}
finally {
MDC.clear();
}
“admin 1234 ERROR – Unable to open file!”
If no key is specified, then the contents of the MDC are sent to the Appender using the format {{key, value}, {key, value}}.
NDC and MDC in Logback
Unlike Log4j, Logback doesn’t provide a native implementation of NDC. However, the slf4j-ext package provides an NDC implementation that uses MDC as its base. You can access and manage MDC values natively in Logback using MDC.put(), MDC.remove(), and MDC.clear():
import org.slf4j.MDC;
...
Logger logger = LoggerFactory.getLogger(MDCLogback.class);
...
MDC.put("username", "admin");
MDC.put("sessionID", "1234");
try {
FileReader fr = new FileReader("tmpFile");
}
catch (Exception ex) {
logger.error("Unable to open file.");
}
finally {
MDC.clear();
}
Adding the following pattern to an Appender in Logback.xml results in the same output as Log4j:
“[admin] 1234 ERROR - Unable to open file.”
MDC access isn’t limited to PatternLayouts. When using the JSONFormatter, for instance, all of the values in the MDC are exported:
{
"timestamp":"1431970324945",
"level":"ERROR",
"thread":"main",
"mdc":{
"username":"admin",
"sessionID":"1234"
},
"logger":"MyClass",
"message":"Unable to open file.",
"context":"default"
}
import org.apache.logging.Log4j.ThreadContext; … ThreadContext.push(username); ThreadContext.push(sessionID); // Logging methods go here ThreadContext.pop(); …
With the Thread Context Map, values are associated with keys just like with MDC:
import org.apache.logging.Log4j.ThreadContext;
...
ThreadContext.put(“username”,"admin");
ThreadContext.put("sessionID", "1234");
// Logging methods go here
ThreadContext.clearMap();
...
ThreadContext provides methods for clearing the stack, clearing the MDC, and clearing all values stored in the Context. Respectively, these methods are ThreadContext.clearAll(), ThreadContext.clearMap(), and ThreadContext.clearStack().
As with MDC and NDC, you can access values in the Thread Context using Layouts. With PatternLayout, the %x conversion pattern retrieves values from the stack while %X and %X{key} retrieves values from the map.
更新列表:
*
参考文章: