Log to a database using log4j

2019-01-06 18:10发布

问题:

Since in log4j javadoc is

WARNING: This version of JDBCAppender is very likely to be completely replaced in the future. Moreoever, it does not log exceptions.

What should I do to log to a database?

回答1:

If you are looking for a database appender which not only works, but also supports connection pooling, is maintained and properly documented, than consider logback's DBAppender.

Ironically enough, the warning in the javadocs about removing JDBCAppender in future versions of log4j was written by me.



回答2:

You can use an alternative appender, but really Log4j 1.2 is going to be around and standard for a long time. They developed DBAppender as part of their receivers companions, which isn't officially released, but you can download the source code and get your own going as well.

Unless the issue of not logging exceptions bothers you, JDBCAppender is just fine. Any further upgrade to 2.0 is going to be more radical than just changing JDBCAppender (if 2.0 happens), so I wouldn't worry about using it, despite the warning. They clearly don't have a solid roadmap or timeline to introducing a new version, and 1.2.15 was released in 2007.



回答3:

    **log4j.properties file**

    # Define the root logger with appender file
    log4j.rootLogger = DEBUG, DB

    # Define the DB appender
    log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender

    # Set JDBC URL
    log4j.appender.DB.URL=jdbc:mysql://localhost/log

    # Set Database Driver
    log4j.appender.DB.driver=com.mysql.jdbc.Driver

    # Set database user name and password
    log4j.appender.DB.user=root
    log4j.appender.DB.password=root

    # Set the SQL statement to be executed.
    log4j.appender.DB.sql=INSERT INTO actionlg(user_id, dated, logger, level, message) values('%X{userId}',' %d{yyyy-MM-dd-HH-mm}','%C','%p','%m')

    # Define the layout for file appender
    log4j.appender.DB.layout=org.apache.log4j.PatternLayout

  **Java Class**  
    Log4jExamples.java
    import java.sql.*;
    import java.io.*;

    import org.apache.log4j.Logger;
    import org.apache.log4j.MDC;


    public class Log4jExample {
           /* Get actual class name to be printed on */
           static Logger log = Logger.getLogger(Log4jExample.class.getName());
           public static void main(String[] args)throws IOException,SQLException{
              log.error("Error");
              MDC.put("userId", "1234");
           }
    }

    **libs required**
     - mysql-connector-java-3.1.8-bin.jar 
     - log4j-1.2.17.jar