我有一个循环。我希望每 20 (100) 次执行查看一些日志。到目前为止,我有一些相当复杂的代码来做到这一点,
for( int i = 0; i < aValues.length; ++i )
{
if( c_LOG.isTraceEnabled() && ( ( i % 20 ) == 0 ) )
{
c_LOG.trace( "Converted item (" + i + ") " );
}
.....
}
这段代码实现了我想要的功能,但是代码很长(4行)并且类似的代码出现了很多次。我无法将其打包到方法中,因为这会导致日志输出中的方法名称困惑。 (log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{3}:(%M %L) %m%n
)有什么好的方法可以解决这个问题吗?
最佳答案
最简单的解决方案就是重构:
for (int i = 0; i < aValues.length; ++i) {
if (shouldLog(i)) {
c_LOG.trace("Converted item (" + i + ")");
}
....
}
....
public boolean shouldLog(int n) {
return shouldLog(n, 20);
}
public boolean shouldLog(int n, int mod) {
return c_LOG.isTraceEnabled() && ((n % mod) == 0);
}
关于java - 如何使用 log4j 记录每 20 个发生的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12627392/