Log4j has three main components: Loggers,appenders and layouts, which can be easily understood as the log category, where the log is to be exported and what form the log outputs. The combination of these three components makes it easy to record the type and level of information and to control the style and location of the log output at run time. The following three components are described separately:
1, loggers
The loggers component is divided into five levels in this system: DEBUG, INFO, WARN, error, and fatal. These five levels are in order, DEBUG < INFO < WARN < ERROR < FATAL, it's important to understand that there is a rule here log4j: Suppose the loggers level is P, if a level q is higher than p in loggers, It can be activated, or it will be shielded.
Java Programs for example:
//建立Logger的一个实例,命名为“com.foo”
Logger logger = Logger.getLogger("com.foo");
//设置logger的级别。通常不在程序中设置logger的级别。一般在配置文件中设置。
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
//下面这个请求可用,因为WARN >= INFO
logger.warn("Low fuel level.");
//下面这个请求不可用,因为DEBUG < INFO
logger.debug("Starting search for nearest gas station.");
//命名为“com.foo.bar”的实例barlogger会继承实例“com.foo”的级别。因此,下面这个请求可用,因为INFO >= INFO
barlogger.info("Located nearest gas station.");
//下面这个请求不可用,因为DEBUG < INFO
barlogger.debug("Exiting gas station search");
Here "is available" means the ability to output logger information.
When naming a logger instance, there is no limit to which you can take any name you are interested in. In general, it is recommended to name the logger instance where the class is located, which is a more effective logger naming method at the moment. This allows each class to establish its own log information for easy management. Like what:
static Logger logger = Logger.getLogger(ClientWithLog4j.class.getName());
2, Appenders
Disabling and using log requests just log4j one of the little places where the log4j log system allows logs to be exported to different places, such as consoles, files, new files based on the number of days or file sizes, streaming to other places, and so on.
The syntax is expressed as:
org.apache.log4j.ConsoleAppender(控制台),
org.apache.log4j.FileAppender(文件),
org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件),org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件),
org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
The configuration is used in the following ways:
log4j.appender.appenderName = fully.qualified.name.of.appender.class
log4j.appender.appenderName.option1 = value1
…
log4j.appender.appenderName.option = valueN
This provides a considerable convenience for the output of the log.