database 使用 log4j 登录到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1364322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Log to a database using log4j
提问by Daniel Moura
回答by Ceki
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.
如果您正在寻找一个不仅可以工作,而且还支持连接池、维护和正确记录的数据库附加程序,那么请考虑 logback 的DBAppender。
Ironically enough, the warning in the javadocs about removing JDBCAppender in future versions of log4j was written by me.
具有讽刺意味的是,javadocs 中关于在 log4j 的未来版本中删除 JDBCAppender 的警告是我写的。
回答by Yishai
You can use an alternativeappender, but really Log4j 1.2 is going to be around and standard for a long time. They developed DBAppenderas part of their receivers companions, which isn't officially released, but you can download the source code and get your own going as well.
您可以使用替代appender,但实际上 Log4j 1.2 将在很长一段时间内成为标准。他们开发了DBAppender作为其接收器伴侣的一部分,该伴侣尚未正式发布,但您也可以下载源代码并自行开发。
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.
除非不记录异常的问题困扰着您,否则 JDBCAppender 就好了。任何进一步升级到 2.0 都将比仅仅更改 JDBCAppender(如果 2.0 发生)更加激进,所以尽管有警告,我也不会担心使用它。他们显然没有推出新版本的可靠路线图或时间表,1.2.15 于 2007 年发布。
回答by AKT
**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