A list,
Log4j (Logger For Java), a logging package For Java logs. Official website. Log4j is an open source project from Apache that provides logging capabilities for Java. Can make programmers very convenient logging, and provides a variety of adaptation, can meet a variety of needs.
To use Log4j, you only need to import a JAR package, jar download address. Maven coordinates are:
<dependency>
<groupId>org.log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.9</version>
</dependency>
Copy the code
Log4j
The Log4j core consists of three main parts:
- Level: indicates the log Level, which defines the importance of a log
- Appender: Appender that defines the log output location
- Layout: defines the log output format
Level (Log Level)
The following is the Log4j Level source code.
Log4j: Log4j Log4j: Log4j
off
: Disable log, the highest level, no log outputfatal
, : Catastrophic error, the highest of all levels that can output logserror
: Error, usually used for exception informationwarn
: warning, generally used for non-standard references and other informationinfo
: Common informationdebug
: Debugging information, usually used during program executiontrace
: Indicates stack information. This parameter is not usedall
: Open all logs, lowest level, all logs can be used
In the Logger core class, each logging level, except for off/all, corresponds to a set of overloaded methods for logging at different levels.
Logs are logged only when the log level corresponding to the method is greater than or equal to the specified log level
Appender (Appender)
Appenders are used to define the output location of logs, and Log4j provides a variety of appends to choose from. Common appends are
Appender | role |
---|---|
ConsoleAppender | Log to the console |
FileAppender | Log to a file |
RollingFileAppender | Logs are recorded in a file, and when the file reaches a certain size, a new file is created |
DailyRollingFileAppender | Log in a file, one backup file per day |
JDBCAppender | Log to a database table |
The above five are commonly used appenders, and the complete list is
Of course, if these do not satisfy your needs, you can:
- implementation
Appender
interfaceimplements Appender
- inheritance
AppenderSkeleton
Class overrides the core method
A: We have a good Layout.
Layout Defines the format of the output log
Layout | format |
---|---|
SimpleLayout | The simple format isLog level - Log content |
TTCCLayout | Time,Thread,Category,Context [Thread] Log level Package name of the logging class. Class name – Log content |
XMLLayout | Output logs in XML format |
HTMLLayout | Output logs in HTML file format |
PatternLayout | Output logs in flexible format. Customize the format using wildcard characters |
The above five are common layouts, and the complete list is
Use Java code for logging
public class Test {
public static void main(String[] args) {
// Get the log object with the current class object
Logger logger = Logger.getLogger(Test.class);
// Set the log level to TRACE
logger.setLevel(Level.DEBUG);
// Create an Appender object
ConsoleAppender conAppender = new ConsoleAppender();
/ / set the Appender
conAppender.setTarget(ConsoleAppender.SYSTEM_OUT);
conAppender.activateOptions();
/ / set the Layout
SimpleLayout simpleLayout = new SimpleLayout();
// Set simpleLayout to Appender
conAppender.setLayout(simpleLayout);
// Add Appender to rootLogger
logger.addAppender(conAppender);
// Log
logger.error("This is the log message."); }}Copy the code
ERROR - This is the log message Process finished with exit code 0Copy the code
This approach is the most intuitive. The code defines the three components of Log4j very intuitively. The disadvantage is that the code is too redundant. As a result, this mode will not be used in actual development (in fact, the reason is that no one uses it, little C just needs some good reason to be professional!!).
7. Use XML file configuration
We can do this in the Resources Root directory (SRC or any source Folder if it’s Eclipse), which is basically the compiled Root directory of the project (think SRC for now). Create a log4j.xml configuration file with the correct location and file name, and add configuration information to the XML file
<?xml version="1.0" encoding="UTF-8"? >
<log4j:configuration>
<appender name="cons" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out"/>
<layout class="org.apache.log4j.SimpleLayout"></layout>
</appender>
<root>
<level value="INFO"></level>
<appender-ref ref="cons"/>
</root>
</log4j:configuration>
Copy the code
For a quick look, this configuration is not actually used in development.
Use properties configuration
We can do this in the Resources Root directory (SRC or any source Folder if it’s Eclipse), which is basically the compiled Root directory of the project (think SRC for now). Create a log4j.properties configuration file with the correct location and file name, and add the configuration information to the properties file
log4j.rootLogger=debug,cons
log4j.appender.cons=org.apache.log4j.ConsoleAppender
log4j.appender.cons.target=System.out
log4j.appender.cons.layout=org.apache.log4j.PatternLayout
log4j.appender.cons.layout.ConversionPattern=%m%n
Copy the code
import org.apache.log4j.*;
public class Test {
public static void main(String[] args) {
// Get the log object with the current class object
Logger logger = Logger.getLogger(Test.class);
// Log
logger.error("This is the log message."); }}Copy the code
The propertis file is the most common configuration method. In the actual development process, the properties file is basically used. A more complete configuration manual is provided in a later section
The configuration mode of the pripertis configuration file is
Log4j. rootLogger= Log level,AppenderA,AppenderB... # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to define a appender -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # define an appender appender names can be arbitrary, # if you want to make the appender to take effect, Must be added to the previous line rootLogger, Behind for the corresponding log4j appenders class. Appender. Appender name = org. Apache log4j. ConsoleAppender log4j.. Appender Appender name. Target = System. Out # Defined log4j appenders layout way. Appender. Appender name. Layout = org.. Apache log4j. SimpleLayoutCopy the code
Java code vs. Properties
Some people think that the Java code is more intuitive, each line is more clear what to do, in fact, Java code and Properties file comparison will find that they are the same, the Properties file configuration does not need to remember a lot of things. For instance
In fact, the properties file is a simplification of Java code. When you interpret properites using Java code, you will find that the results are basically the same
Ten,
To summarize, the log4j configuration file’s main architecture is
Log4j. rootLogger= Log level, AppenderNameA, . Log4j. Appender. AppenderNameA = to use appender log4j. Appender. AppenderNameA. PropertyA = PropertyA value . Log4j appenders. AppenderNameA.. PropertyB = value of PropertyB log4j appenders. AppenderNameA. PropertyC = PropertyC value . Log4j appenders. AppenderNameA. Layout = to use the layout of log4j. Appender. AppenderNameA. Layout. PropertyA = PropertyA value Log4j. Appender. AppenderNameA. Layout.. PropertyB = value of PropertyB log4j appenders. AppenderNameA. Layout. PropertyC = PropertyC valueCopy the code
PropertyA is the property corresponding to the setXxxx method in the previous class, for example:
log4j.appender.cons=org.apache.log4j.ConsoleAppender
log4j.appender.cons.target=System.out
Copy the code
Which means that
ConsoleAppender cons = new ConsoleAppender();
cons.setTarget("System.out");
Copy the code
If the set method argument is an object type, then the package name of the corresponding type is written. Class name, for example
log4j.appender.cons=org.apache.log4j.ConsoleAppender
log4j.appender.cons.layout=org.apache.log4j.SimpleLayout
Copy the code
Which means that
ConsoleAppender cons = new ConsoleAppender();
SimpleLayout simpleLayout = new SimpleLayout();
cons.setLayout(simpleLayout);
Copy the code
So, even if you forget what to configure, just take a look at the source code
Xi. Appendix
1. Large Properties file
. # # set the global log LEVEL can use log4j appenders. XXX. Threshold = LEVEL set log LEVEL for a specific appender appender # set all came into effect, not appear in the appender here, Even defines the invalid log4j. RootLogger = debug, cons, myFile, myrFile, mydFile, JDBC # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = console logging = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = log4j. Appender. Cons = org.. Apache log4j. ConsoleAppender # set the current log level for appenders info, When the method of priority is greater than the info. The console will be output log4j appenders. The cons. The threshold = info # set the log output mode, System. The out and System.. Err two choices log4j appenders. The cons. The target = System. Out # is set to true, said to create a new System. The out object, . Do not use the System in the class out attributes log4j appenders. Cons. Follow = true. Log4j appenders. The cons. The layout = org). Apache log4j. SimpleLayout # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = file logging = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Log4j. Appender. MyFile = org, apache log4j. FileAppender # file storage path log4j appenders. MyFile. The file =. / the TXT # whether in the form of supplementary to write the content in the log file, Defaults to true and does not overwrite the previous content, Otherwise will only retain the last write logs log4j. Appender. MyFile. Append = false. Log4j appenders. MyFile. Layout = org). Apache log4j. SimpleLayout # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = scroll file Logging = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # when the log reaches a certain size, . Will create a new file to log the log4j appenders. MyrFile = org.. Apache log4j. RollingFileAppender log4j. Appender. MyrFile. The file =. / the TXT # Maximum number of files to be backed up. If the file size exceeds the specified value, the original files will be backed up. # this value specifies the number of backup files, if more than the number, will delete the earliest backup files, if zero is not backed up log4j. Appender. MyrFile. The maximum capacity of the maxBackupIndex = 5 # for each one The default unit is b, You can specify "KB", "MB", or "GB" to back up files when they exceed this size (maxBackupIndex! . = 0) log4j appenders. MyrFile. MaxFileSize = 1024 # maximum capacity for each file, similar to the maxFileSize, is long, however, that there shall be no unit, Unit is b log4j appenders. MyrFile. MaximumFileSize = 1024 log4j appenders. MyrFile. Layout = org). Apache log4j. SimpleLayout # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = rolling file daily Logging = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # log backups according to day Log4j. Appender. MydFile = org. Apache. Log4j. DailyRollingFileAppender # the previous log backup file suffix format (suffix as the date the day before, Format for the date format) log4j. Appender. MydFile. The datePattern = yyyyMMdd # the day's records of log file path log4j. Appender. MydFile. The file =. / nl. TXT Log4j. Appender. MydFile. Layout = org.. Apache log4j. SimpleLayout # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = JDBC logging = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # select JDBC recorder log4j. Appender. JDBC = org.. Apache log4j. JDBC. JDBCAppender # driver Log4j. Appender. JDBC. Driver = com. Mysql.. JDBC driver # password log4j. Appender. JDBC. Password = # url Log4j. Appender. JDBC URL = JDBC: mysql: / / localhost: 3306 / log # username log4j appenders. JDBC. User = # root database insert statement SQL =. Log4j appenders. JDBC. Insert into t_log values (' % m ') # layout log4j. Appender. JDBC. Layout = org.. Apache log4j. SimpleLayoutCopy the code
PatternLayout output format
format | role |
---|---|
%p | The log level |
%d | The 2018-6-26 date 16:05:19, 555 |
%d{ymdhms custom date format} | %d{yyyyMMddHHmmss} |
%r | Time spent logging |
%C | The name of the package that generated the log. The name of the class |
%t | The name of the thread that generated the log |
%m | Log message |
%l | The name of the package that generated the log. Class name. Method name (class name: line number) |
%L | The line Numbers |
Such as:
log4j.appender.cons.layout=org.apache.log4j.PatternLayout
log4j.appender.cons.layout.ConversionPattern= [%p] %d %c - %m%n
Copy the code
For complete format configuration, see the official API
Your thumbs-up is the biggest support for small C! It is also the motivation for Little C to continue sharing. Thank you for your support. Thank you