我正在尝试在我的应用程序上运行log4j 2.0。在我的应用程序中,我设置了两个记录器:
一个可以将内容输出到控制台,以便您了解发生了什么。
另一个将测试运行结果输出到DB2表中。这是一个完全不同的日志,仅用于跟踪运行测试的时间和结果。
我的麻烦是使用DB2记录器。我似乎无法将记录写到表中。我知道我快到了,因为:
如果使用虚拟库或表名,则在配置过程中会出现log4j错误。
如果我使用伪造的用户名或密码,则在配置期间会出现log4j错误。
如果我使用对文件无权限的有效用户名/密码,则在配置期间会出现log4j错误。
但是...如果所有这些事情都正确,则不会出错,也不会写入任何记录。
在控制台中,我可以看到log4j重新配置正确完成:
2013-10-02 11:31:06,261 DEBUG Reconfiguration completed
所以...我想念什么?在log4j网站上没有太多文档。
这是应用程序中的代码:
public static void testExists(String myProcedure) {
final Logger console = LogManager.getLogger(myProcedure);
final Logger mytestlog = LogManager.getLogger(myProcedure);
.... yadda, yadda, yadda ....
.... and then finally, call the loggers with ....
console.info("== write this to the console ==");
mytestlog.info("== write this to the db2 log ==");
}
这是我的log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="trace">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%date{HH:mm:ss.SSS} %-5level{lowerCase=false} %logger{36} | %msg%n"/>
</Console>
<JDBC name="jdbc" tableName="vqccommon.sptestlog">
<ConnectionFactory class="foo.bar.chew.Log4jConnect" method="log4jConnect" />
<Column name="timestamp" isEventTimestamp="true" />
<Column name="testclass" pattern="%class" />
... some other columns ....
</JDBC>
</Appenders>
<Loggers>
<Logger name="sptestlog" level="trace">
<AppenderRef ref="jdbc" ></AppenderRef>
</Logger>
<Root level="trace">
<AppenderRef ref="Console" ></AppenderRef>
</Root>
</Loggers>
</Configuration>
最佳答案
正如porfiriopartida在评论中提到的,我认为您已经快到了,但是您只需要更改在(测试)应用程序中创建Logger的方式即可:
public static void testExists() {
Logger console = LogManager.getLogger(getClass());
Logger dbLog = LogManager.getLogger("sptestlog"); // match config Logger name!
console.info("== write this to the console ==");
dbLog.info("== write this to the db2 log ==");
}
只有使用
LogManager.getLogger("sptestlog")
创建的记录器才会追加到您配置的JDBC追加器中。具有任何其他名称的记录器将记录到控制台。2013-10-02 11:31:08,224 DEBUG ServletContext not present - WebLookup not added
行与JDBC日志记录无关。 Log4J在Web容器中进行了一些额外的初始化。如果找不到Web容器,则不需要进行初始化。