1. Three Main Components:
1) Logger
2) Appender
3) Layout
These three types of components work together to enable developers to log message according to message type and level, and to control at runtime how these messages are formatted and where they are reported.
Relationship between these important components
2. Logger may be assigned levels.
1) TRACE
2) DEBUG
3) INFO
4) WARN
5) ERROR
6) FATAL
If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level.
Inside it is managed by LoggerManager. Which has a map set the name as key, and the Logger as value.
3. Appender
1) Log4j allows logging requests to print to multiple destinations.
2) Main sub class of Appender
1) ConsoleAppender
2) FileAppender/RollingFileAppender
3) JMSAppender
4) SMTPAppender
5) JDBCAppender
6) SocketAppender
3) A Logger may have multiple Appender.
Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. <Observer Design Pattern>
In other words, appenders are inherited additively from the logger hierarchy.
For example, if a console appender is added to the root logger, then all enabled logging requests will at least print on the console.
4. Layout
1) More often than not, users wish to customize not only the destination but also the output format.
This is accomplished by associating a layout with an appender.
2) The hierarchy of Layout is shown as below.
5. A simple example of using Log4j
1) pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>edu.xmu.logging</groupId> <artifactId>Logging-Log4J</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> </dependencies> </project>
2) log4j.properties in the class path
# Define the root logger with appender X log = C:/YangKunLun/logging log4j.rootLogger = ERROR, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender # Set the name of the file log4j.appender.FILE.File=${log}/log.out # Set the immediate flush to true(default) log4j.appender.FILE.ImmediateFlush=true # Set the threshold to debug mode log4j.appender.FILE.Threshold=debug # Set the append to true, override log4j.appender.FILE.Append=true # Set the maxmium file size before rollover # log4j.appender.FILE.MaxFileSize=5KB # Set the date pattern log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-HH-mm # Set the backup index # log4j.appender.FILE.MaxBackupIndex=2; # Define the layout for X appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n
3) Log4jExampleTest.java
package edu.xmu.log4j; import java.util.Date; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Test; public class Log4jExampleTest { private static Logger logger = Logger.getLogger("edu.xmu"); static { logger.setLevel(Level.INFO); } @Test public void test() { // Debug < Info < Warn < Error < Fatal logger.debug((new Date()) + " [DEBUG] Hello this is an debug message"); logger.info((new Date()) + " [INFO] Hello this is an info message"); logger.warn((new Date()) + " [WARN] Hello this is an warn message"); logger.error((new Date()) + " [ERROR] Hello this is an error message"); logger.fatal((new Date()) + " [FATAL] Hello this is an fatal message"); } }
4) Log4jExampleTest2.java
package edu.xmu.log4j; import java.util.Date; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.junit.Test; public class Log4jExampleTest2 { private static Logger logger = Logger.getLogger("edu.xmu.log4j"); @Test public void test() { // Log4jExampleTest test = new Log4jExampleTest(); Layout layout = new SimpleLayout(); Appender appender = new FileAppender(); appender.setLayout(layout); logger.addAppender(appender); logger.debug((new Date()) + " [DEBUG] Hello this is an debug message"); logger.info((new Date()) + " [INFO] Hello this is an info message"); logger.warn((new Date()) + " [WARN] Hello this is an warn message"); logger.error((new Date()) + " [ERROR] Hello this is an error message"); logger.fatal((new Date()) + " [FATAL] Hello this is an fatal message"); } }
Comments:
1) When we de-comment the comments in Log4jExampleTest2.java, we can find that the level of this logger in this class is no longer that inherits from RootLogger that is ERROR.
But inherits from "edu.xmu" which is INFO.
6. Configuration file in depth
1) You may wonder there are so many differents choice for us to choose from. How can we remember all the properties in order to config the configuration file properly?
Let take a look at a simple configuration file.
# Here we define the root logger for log4j. # The syntax of defining root logger is : # log4j.rootLogger = "RootLevel", "RootAppender1", "RootAppender02" # Here we using "STDOUT" as micro variables. log4j.rootLogger = INFO, STDOUT # Here we specify what the STDOUT is. # As STDOUT must be an Appender. # Here we specify that STOUT is the instance of ConsoleAppender # So every time we encounter log4j.appender.STDOUT, we can use "org.apache.log4j.ConsoleAppender" as replacement. log4j.appender.STDOUT = org.apache.log4j.ConsoleAppender # Then we dig into the source code of "org.apache.log4j.ConsoleAppender" # We can find a method named public void setTarget(String value) # So we can set as below: log4j.appender.STDOUT.Target = System.out # It equals : org.apache.log4j.ConsoleAppender.setTarget("System.out");
2) Extends
Let's take a look at the more complex configuration file
<log4j.logger.edu.xmu is a custom logger that defined in configuration file>
<When we want to get this custom logger, we just use Logger.getLogger("edu.xmu");>
Please pay attention that we ignore the prefix of "log4j.logger" when getting the logger.
# Here we define macro named "log" whose value is "c:/..." log = C:/YangKunLun/logging # Here we define the default level for root loggger # And added two Appenders for this root logger log4j.rootLogger = INFO, FILE, STDOUT log4j.logger.edu.xmu = WARN, FILE, STDOUT # This has been explained in example above log4j.appender.STDOUT = org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.Target = System.out # Here we define the log4j.appender.FILE is an instance of DailyRollingFileAppender log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender # When we look up the class org.apache.log4j.DailyRollingFileAppender # We can find a method named setFile(String file) # This means we want to set the output file as "c:/yangkunlun/logging/log.out" log4j.appender.FILE.File=${log}/log.out # We have to define the Layout for each Appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n log4j.appender.STDOUT.layout = org.apache.log4j.PatternLayout # Regard configuration file as java code.
7. Code configuration in depth
package edu.xmu.log4j; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Date; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.junit.Test; public class Log4jExampleTest2 { private static Logger logger = Logger.getLogger("edu.xmu.log4j"); @Test public void test() throws IOException { // Log4jExampleTest test = new Log4jExampleTest(); Layout layout = new SimpleLayout(); ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.setName("SYSOUT"); consoleAppender.setLayout(layout); consoleAppender.setWriter(new OutputStreamWriter(System.out)); consoleAppender.setThreshold(Level.ERROR); FileAppender fileAppender = new FileAppender(); fileAppender.setName("FILE"); fileAppender.setLayout(layout); fileAppender.setAppend(true); fileAppender.setImmediateFlush(true); fileAppender.setWriter(new FileWriter(new File( "C:/YangKunLun/logging/log2.out"))); fileAppender.setThreshold(Level.DEBUG); logger.addAppender(fileAppender); logger.addAppender(consoleAppender); logger.setLevel(Level.WARN); logger.debug((new Date()) + " [DEBUG] Hello this is an debug message"); logger.info((new Date()) + " [INFO] Hello this is an info message"); logger.warn((new Date()) + " [WARN] Hello this is an warn message"); logger.error((new Date()) + " [ERROR] Hello this is an error message"); logger.fatal((new Date()) + " [FATAL] Hello this is an fatal message"); } }
Comments:
1) The code above is equivalent to the configuration file in 6-2
2) Pay attention to that fileAppender.setWriter(new FileWriter(...)) is not fileAppender.setFile("...");
Pay attention to that console.setWriter(new OutputStreamWriter(...)) is not consoleAppender.setTarget("...");
3) The relationship of levels of Logger and Appender is like that in JUL. Please refer to previous chapter.
Reference Links:
1) http://logging.apache.org/log4j/1.2/manual.html
相关推荐
针对Log4j 2 远程代码执行漏洞,需要用到的升级资源包,适用于maven资源库,包括log4j,log4j-core,log4j-api,log4j-1.2-api,log4j-jpa等全套2.15.0 maven资源库jar包。如果是maven本地仓库使用,需要将zip包解压...
这次我们关注的是其最新版本——logging-log4j2-log4j-2.15.0-rc2。这个版本在安全性和性能上都做了进一步的优化和提升,旨在为开发者提供更高效、更安全的日志处理方案。 1. **Log4j 2概述**: Log4j 2是Log4j的...
总的来说,"logging-log4j2-log4j-2.16.0-rc1.zip"的发布是Log4j团队对"Log4Shell"漏洞的有力回应,通过禁用可能导致安全问题的功能,提高了整体的安全标准。这一事件提醒我们,安全无小事,及时的更新和维护是保障...
Apache Log4j 2.3 和 Commons Logging 1.2 是两个在Java Web开发中广泛使用的日志处理库。这两个库对于记录应用程序的运行时信息、调试错误和监控系统状态至关重要。 **Apache Log4j 2.3** Log4j 是 Apache 组织...
Log4j是一个广泛应用于Java环境的日志框架,而当我们谈论`android-logging-log4j-1.0.3.jar`时,它便是Log4j的一个版本,专门针对Android平台进行优化,使得在Android系统中可以方便地将日志信息写入SD卡。...
"commons-logging.jar" 和 "log4j.jar" 是两个广泛使用的Java日志框架,它们在Java应用开发中扮演着至关重要的角色。 **commons-logging.jar** 是Apache Commons Logging库,它提供了一个统一的日志接口,允许...
"log4j.jar" 和 "commons-logging.jar" 是两个非常著名的Java日志库,它们在Java日志处理中扮演着核心角色。 **log4j.jar** 是Apache软件基金会开发的一个开源日志框架,它为Java应用程序提供了灵活的日志记录解决...
Log4j,作为Apache开源组织的一个杰出项目,长期以来一直是Java应用程序首选的日志框架之一。然而,随着技术的发展,安全问题也日益凸显,Log4j 2.15.1-RC1的发布,正是针对此类问题进行的一次关键更新,旨在修复...
《log4j 2.15.0-rc2:Apache Logging服务的强化与更新》 在IT领域,日志管理是系统监控和故障排查的关键环节。Apache Log4j作为一个广泛应用的日志记录框架,为Java开发者提供了强大的日志处理能力。最近发布的...
"android-logging-log4j-1.0.3"是一个专为Android平台定制的log4j版本,它将log4j的功能集成到Android环境中,使得开发者可以享受到log4j的强大功能。这个版本号"1.0.3"表示这是该库的一个特定发行版,可能包含了...
标签:apache、logging、log4j、slf4j、impl、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和...
然后使用Logger.getLogger()方法获取日志记录器,而Log4j2需要import org.apache.logging.log4j.Level、org.apache.logging.log4j.LogManager和org.apache.logging.log4j.Logger,使用LogManager.getLogger()方法...
标签:core、apache、logging、log4j、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译...
`log4j`是Apache组织提供的一款开源的日志记录框架,广泛应用于Java环境中。本文将深入探讨`log4j`在日志记录中的应用及其重要性。 **Log4j简介** `log4j`是一个强大的、灵活的、可扩展的日志记录工具,其设计目标...
logging-log4j2, Apache日志记录Log4J2镜像 Apache Log4J 2Apache是对 Log4J的升级,它提供了比它的前辈 Log4J 1. x,的显著改进,并提供了许多改进,同时解决了soa架构中一些固有问题。 在Github上请求请求通过发送...
Apache log4j2零日漏洞,根据 log4j-2.15.0-rc2 版本编译生成log4j-api-2.15.0.jar 1.解压你的jar jar xvf XXX.jar 2. 删除旧版本jar cd ./BOOT-INF/lib rm -rf log4j-api-*.jar 3. 上传新版本log4j-api-2.15.0....
Apache Commons Logging和Log4j是两个广泛使用的日志框架,本指南将深入讲解如何将它们结合使用,为你的Java应用程序提供强大的日志功能。 首先,让我们了解Apache Commons Logging。它是Apache软件基金会的一个...
《深入理解Log4j:基于logging-log4j-1.2.13.zip的解析》 Log4j是Apache组织开发的一款广泛使用的日志记录框架,尤其在Java应用程序中,它的身影无处不在。本文将深入探讨logging-log4j-1.2.13版本中的核心概念、...
Log4j,作为Java平台上的一个著名日志框架,因其高效、灵活的特点而广受欢迎。然而,任何软件都可能存在潜在的安全风险,Log4j也不例外。这次我们要讨论的是Log4j 2.15.0-rc1版本,这是一个针对严重安全漏洞的修复...