Java:apache log4j Concise Course (ii)

Source: Internet
Author: User

The basic concepts of log4j, the configuration file, and the method of writing the log to the file are described in a concise tutorial on Apache log4j (i), and a detailed example is given. In this talk, I'm going to talk about how to use log4j to write logs to the MySQL database.

Writing a log to a database requires experience (1) establishing a MySQL database logging table, (2) Configuring the log4j configuration file, (3) Writing a Java execution program in three major steps, and the details of the three steps are described below.

  Create a MySQL database log record table

Because each person wants to record the log information in the MySQL database, the tables created are different, and a practical example is given below:

 Use' Logs 'CREATE TABLElog4j (LogidINTAuto_incrementPRIMARY KEY  not NULL, LogdateVARCHAR(Ten), LogclientipVARCHAR( the), LogNameVARCHAR(255), LogLevelVARCHAR(5), LogmsgVARCHAR(255));

  Configure Log4j.properties

The data source is db when the log is written to MySQL, and the detailed implementation class is Jdbcappender. The configuration parameters related to MySQL connection in Jdbcappender are as follows:

Driver Set the driver for the connection database, such as the MySQL driver string: com.mysql.jdbc.Driver;
Url Sets the connection string for the database;
User Set the user name of the database;
Password Set the password for the database;
Sql Sets the SQL statement of the operational database;

See the following example for a detailed configuration:  

# Define The root logger with Appender Filelog4j.rootlogger=DEBUG, db# Define the DB appenderlog4j.appender.DB=org.apache.log4j.jdbc.jdbcappender# Set jdbc URLlog4j.appender.DB.URL=jdbc:mysql://192.168.31.221/logs# Set Database Driverlog4j.appender.DB.driver=com.mysql.jdbc.driver# Set Database user name and Passwordlog4j.appender.DB.user=Testlog4j.appender.DB.password=test# Set The SQL statement to be Executed.log4j.appender.DB.sql=insert into log (logdate, Logclientip, LogName, LogLevel, logmsg) VALUES ('%d ', '%x{clientip} ', '%c ', '%p ', '%m ') # Define the layout forfile Appenderlog4j.appender.DB.layout=org.apache.log4j.patternlayout

  The issue of how configuration files are configured has been explained in the previous lecture and is no longer redundant here . The XML format configuration file is referenced as follows:

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE log4j:configuration SYSTEM "Log4j.dtd"><log4j:configuration><Appendername= "DB"class= "Org.apache.log4j.jdbc.JDBCAppender">   <paramname= "url"value= "Jdbc:mysql://localhost/logs"/>   <paramname= "Driver"value= "Com.mysql.jdbc.Driver"/>   <paramname= "User"value= "Test"/>   <paramname= "Password"value= "Test"/>   <paramname= "SQL"value= "INSERT into log (logdate, Logclientip, LogName, LogLevel, logmsg) VALUES ('%d ', '%x{clientip} ', '%c ', '%p ', '%m ')" />      <Layoutclass= "Org.apache.log4j.PatternLayout">   </Layout></Appender><Loggername= "Log4j.rootlogger"additivity= "false">   < Levelvalue= "DEBUG"/>   <Appender-refref= "DB"/></Logger></log4j:configuration>

  Writing Java Execution programs

1  PackageOrg.warnier.zhang.demo;2 3 Importjava.net.InetAddress;4 Importjava.net.UnknownHostException;5 6 ImportOrg.apache.log4j.Logger;7 ImportOrg.apache.log4j.MDC;8 9  Public classTest {Ten  One     Private StaticLogger Logger = Logger.getlogger (Test.class); A  -      Public Static voidMain (string[] args)throwsunknownhostexception { -         /** the * Obtain the IP of the client; -          */ -InetAddress inetaddress =inetaddress.getlocalhost (); -String ClientIP =inetaddress.gethostaddress (); +Mdc.put ("ClientIP", ClientIP); -          +Logger.trace ("Trace > Start logging ..."); ALogger.debug ("Debug > Start Logging ..."); atLogger.info ("info > Start logging ..."); -Logger.warn ("Warn > Start logging ..."); -Logger.error ("error > Start logging ..."); -Logger.fatal ("Fatal > Start logging ..."); -     } -  in}

is that the end of it? The reader may ask: "There is no JDBC operation in the Java program, how is the log written to MySQL data?" "In fact, in the previous talk, log4j adopted a mechanism to write logs directly to the database, in other words, the operation of the database has been contracted by the LOG4J framework itself." The attentive reader can see that the log is not involved in the file when it was written in the previous lecture, as in the same reason. Also need to mention is, although this blog is to use the MySQL database to tell, but do not mistakenly think that log4j incompatible with other databases, in fact, as long as the relational database, the above configuration files are configured appropriately, log4j can be well supported.

Put your own processing results on the following:

Java:apache log4j Concise Course (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.