我正在运行一个gradle项目,我试图让log4j既登录到控制台又登录到文件。将错误记录到控制台时,不会记录任何文件。我在src / main / resources中有我的log4j.properties。我已经尝试将属性文件移动到src文件夹以及几乎所有在SO上建议的文件夹都没有成功。我也在log4j中尝试过rollingFile和File。 log4j.properties文件是否有问题,或者我没有将文件放在正确的位置?
以下是我当前的文件
log4j.properties
# root level configurations
log4j.rootLogger=INFO,console,rollingFile
# configuration for console outputs
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# configuration for file output (into a file named messages.log)
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=/home/cbolles/devel/testing/gradle_testing/messages.log
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
的build.gradle
apply plugin: 'java'
repositories {
jcenter()
}
dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.8.2'
compile 'org.slf4j:slf4j-log4j12:1.7.18'
testCompile 'junit:junit:4.12'
}
task(runSimple, dependsOn: 'classes', type: JavaExec) {
main = 'com.bolles.ErrorTester'
classpath = sourceSets.main.runtimeClasspath
args 'mrhaki'
systemProperty 'simple.message', 'Hello '
}
defaultTasks 'runSimple'
LogTesting.java
package com.bolles;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogTesting
{
private static final Logger log = LogManager.getLogger(LogTesting.class);
public static void reportError(Exception e, boolean consoleLog)
{
String errorMessage = "";
if(e.getMessage() != null)
{
errorMessage = e.getMessage();
}
StringWriter stackTraceWriter = new StringWriter();
e.printStackTrace( new PrintWriter(stackTraceWriter));
String stackTrace = stackTraceWriter.toString();
log.error(errorMessage);
log.log(Level.ERROR, errorMessage + "\n" + stackTrace);
}
}
ErrorTester.java
package com.bolles;
public class ErrorTester
{
public static void nullStringTest()
{
String errorString = null;
try
{
System.out.print(errorString);
}
catch(Exception e)
{
LogTesting.reportError(e, true);
}
}
public static void main(String[] args)
{
nullStringTest();
}
}
其他答案似乎都不适用于我的问题。
答案 0 :(得分:0)
明显的问题似乎是你正在使用log4j的LogManager和Logger类。对LogTesting类进行以下更改(正如我所见,slf4j已经在您的依赖项中)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
private static final Logger log = LoggerFactory.getLogger(LogTesting.class);
...
log.error(errorMessage);
//log.log(Level.ERROR, errorMessage + "\n" + stackTrace); //no such method in slf4j
它应该按预期在文件中写入错误。
(你似乎也需要修改ErrorTester类,因为当前没有抛出异常,因此不会调用LogTesting.reportError())