Use log4j to write logs to the database

Source: Internet
Author: User
Tags log log

The previous project has such a requirement. In the log management system, some log information needs to be stored in the database for users and administrators to view and analyze. So it took me some time to implement this function. Please refer to it. Abstract: We know that log4j provides powerful and configurable logging functions, including file writing and printing to the console. However, sometimes we need it to output logs to the background database, the powerful scalability of log4j supports this. The following is the specific implementation. Key words: log, log4j, log, Java, DB, database, slf4j prerequisites: slf4j and log4j have been configured, and logs can be normally written to files or the console. Requirement: Write logs to the database. English version (the use of log4j-1.2.17.jar, slf4j-api-1.7.5.jar, slf4j-log4j12-1.6.6.jar.

Step 1: you must first be able to write data to the database and write an interface that can write data to the database log table, whether it is WebService or something, here is a Java interface.
Log is a defined Log class. You can use the LogService object to call the logBll. add (log Log) method to add a Log to the database.
123456789 public class Log {    private Long id;    private String logNum;    private String userId;    private Calendar time;    private int type;    private String content;    ...}

Step 2: compile a class that inherits the AppenderSkeleton class and override its append method. The append method calls the Java interface defined in the previous step. logBll. add (log) writes a log to the database.
12345678910111213141516 public class DBAppender extends AppenderSkeleton {     private LogService logBLL = new LogService();     @Override    protected void append(LoggingEvent arg0) {        if (!arg0.getLoggerName().startsWith(Constants.ProjetNS))            return;        Log log = new Log();        log.setType(arg0.getLevel().toInt());        log.setTime(Calendar.getInstance());        log.setUserId("system");        log.setContent(arg0.getRenderedMessage());        logBll.add(log);    }}
Step 3:

Change the log4j. properties configuration file, as shown below.

 

1234567891011121314151617 # Root logger optionlog4j.rootLogger=WARN, stdout, file, db # Direct log messages to stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.appender.file = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.File = logs/log.loglog4j.appender.file.Append = truelog4j.appender.file.Threshold = ERRORlog4j.appender.file.layout = org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n log4j.appender.db = com.aitanjupt.angel.log.DBAppender 
The above file mainly adds a log output direction, outputs to the database, and specifies a specific processing class. To output logs, use private Logger logger = LoggerFactory. getLogger (SpringServiceSupport. class); logger. error (ex.



From Weizhi note (Wiz)



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.