##############################
Log4j.appender.r=org.apache.log4j.jdbc.jdbcappende
Log4j.appender.r.url=jdbc:mysql://localhost/log4jdem
Log4j.appender.r.user=defaul
Log4j.appender.r.password=default
Log4j.appender.r.sql=insert into jdbctest (message) VALUES ('%d-%c-%p-%m ')
##################################################
The first line tells Log4j,r is the type of jdbcappender. The second line declares the URL of the database that we want to log.
The third line, four lines is the username and password, used to log into the database. The last line is the SQL query statement to execute.
We'll talk more about this configuration.
Developers who have used JDBC immediately recognize the similarities between declaring these values and commonly used JDBC. For any
Jdbc-compliant program, these are the values that you should specifically point out. Of course, you will need to change these values to reflect your own program. For example,
If you are writing logs to Oracle, the URL in the above example will become
Jdbc:oracle:thin: @yourhostSID. Also, it is important to note that these drivers should be available for your program, in other words, LOG4J will visit them. Let's talk about that final description now. The SQL you use to log in to the database will be changeable and can be changed according to your needs. The table I use for log below is called
Jdbctest:date (%d), Category/logger (%c), priority (%p), and message (%M) is a column, called a message. The log4j
collects these instructions, passes through a formatter, returns and replaces the matching samples with the actual values. The format device is associated with the special layout of the Appender.
Then, log4j, simply executes the formatted SQL.
If you want, you can record different things in different columns. For example, another valid directive would be:
INSERT into jdbctest (Date, Logger, Priority, message) VALUES ('%d ', '%c ', '%p ', '%m ') This will mean that in our database we can use the appropriate columns (Date, Logger, Priority, and message). To define your own jdbctest
. You can test this program with JDBC by specifically specifying the config-jdbc.properties path as a parameter in the Startupservlet.
So, what code modifications need to be logged to the database. There is no code. This is the powerful place that log4j shows itself
. We don't need to change a line of code to log logs into the database. We use only a different profile and the correct parameters. The
log descriptions that used to appear in the console are now written directly to the Jdbctest table in your database.