在添加log4j到我的应用程序后,每次执行我的应用程序时,我都会得到以下输出:

log4j:WARN No appenders could be found for logger (slideselector.facedata.FaceDataParser).
log4j:WARN Please initialize the log4j system properly.

这似乎意味着一个配置文件丢失了。 这个配置文件应该放在哪里,一个好的开始内容是什么?

我正在使用纯java开发桌面应用程序。所以没有网络服务器等等…


当前回答

Maven的解决方案:

我遇到了所有与上面相同的问题,对于maven解决方案,我使用了2个依赖项。如果您希望一个简单的项目使用一个标准配置的日志记录器,那么此配置仅用于快速测试。我可以想象,如果您需要更多信息或调整自己的日志级别,您稍后会想要制作一个配置文件。

    <properties>
        <slf4jVersion>1.7.28</slf4jVersion>
    </properties>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4jVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>${slf4jVersion}</version>
        </dependency>

其他回答

如果您在Intellij IDEA上出现此错误,即使添加了log4j。如果您的资源测试文件夹中存在log4j. properties或log4j.xml文件,可能Intellij IDEA还不知道该文件的存在。

因此,在添加文件之后,右键单击该文件并选择Recompile log4j.xml。

另一种不将属性文件放在类路径上的方法是直接从java代码中设置属性。下面是示例代码。

public class Log4JSample {

public static void main(String[] args) {
    Properties properties=new Properties();
    properties.setProperty("log4j.rootLogger","TRACE,stdout,MyFile");
    properties.setProperty("log4j.rootCategory","TRACE");

    properties.setProperty("log4j.appender.stdout",     "org.apache.log4j.ConsoleAppender");
    properties.setProperty("log4j.appender.stdout.layout",  "org.apache.log4j.PatternLayout");
    properties.setProperty("log4j.appender.stdout.layout.ConversionPattern","%d{yyyy/MM/dd HH:mm:ss.SSS} [%5p] %t (%F) - %m%n");

    properties.setProperty("log4j.appender.MyFile", "org.apache.log4j.RollingFileAppender");
    properties.setProperty("log4j.appender.MyFile.File", "my_example.log");
    properties.setProperty("log4j.appender.MyFile.MaxFileSize", "100KB");
    properties.setProperty("log4j.appender.MyFile.MaxBackupIndex", "1");
    properties.setProperty("log4j.appender.MyFile.layout",  "org.apache.log4j.PatternLayout");
    properties.setProperty("log4j.appender.MyFile.layout.ConversionPattern","%d{yyyy/MM/dd HH:mm:ss.SSS} [%5p] %t (%F) - %m%n");

    PropertyConfigurator.configure(properties);

    Logger logger = Logger.getLogger("MyFile");

    logger.fatal("This is a FATAL message.");
    logger.error("This is an ERROR message.");
    logger.warn("This is a WARN message.");
    logger.info("This is an INFO message.");
    logger.debug("This is a DEBUG message.");
    logger.trace("This is a TRACE message.");
}

}

虽然正确地设置log4j对于“真正的”项目很好,但你可能想要一个快速而肮脏的解决方案,例如,如果你只是在测试一个新库。

如果是,则调用静态方法

org.apache.log4j.BasicConfigurator.configure();

将在控制台设置基本日志记录,错误消息将消失。

如果你把所有东西都扔掉(比如你在考试)

org.apache.log4j.BasicConfigurator.configure(new NullAppender());

Logging API - The Java Logging API facilitates software servicing and maintenance at customer sites by producing log reports suitable for analysis by end users, system administrators, field service engineers, and software development teams. The Logging APIs capture information such as security failures, configuration errors, performance bottlenecks, and/or bugs in the application or platform. The core package includes support for delivering plain text or XML formatted log records to memory, output streams, consoles, files, and sockets. In addition, the logging APIs are capable of interacting with logging services that already exist on the host operating system.

logging包«提供Java平台核心日志工具的类和接口。


Log4j 1。x«log4j是一个流行的基于java的日志记录实用工具。Log4j是一个基于许多作者工作的开放源码项目。它允许开发人员通过使用Appenders[控制台,文件,DB和电子邮件]来控制哪些日志语句输出到不同的位置。它可以在运行时使用外部配置文件进行完全配置。

Log4j有三个主要组件: 记录器-[关闭,致命,错误,警告,信息,调试,跟踪] 输出源 Apache公共日志:ConsoleAppender, FileAppender, RollingFileAppender, DailyRollingFileAppender, jdbcapappender - driver, SocketAppender Log4J Appender for MongoDB: MongoDbAppender - Driver 布局- [PatternLayout, EnhancedPatternLayout]


配置文件可以用XML或Java属性(key=value)格式编写。

log4j_External。Java属性(键=值)格式 开始的“${”和结束的“}”之间的字符串被解释为键。替换变量的值可以定义为系统属性,也可以定义为配置文件本身。 设置附加器特定的选项。«log4j.appender.appenderName。对于每个命名的appender,你可以配置它的布局。

log4j.rootLogger=INFO, FILE, FILE_PER_SIZE, FILE_PER_DAY, CONSOLE, MySql

#log.path=./
log.path=E:/Logs

# https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
# {%-5p - [WARN ,INFO ,ERROR], %5p 0- [ WARN, INFO,ERROR]}
log.patternLayout=org.apache.log4j.PatternLayout
log.pattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n

# System.out | System.err
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.err
log4j.appender.CONSOLE.layout=${log.patternLayout}
log4j.appender.CONSOLE.layout.ConversionPattern=${log.pattern}

# File Appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log.path}/logFile.log
#log4j:ERROR setFile(null,false) call failed. - Defaults setFile(null,true)
#log4j.appender.FILE.Append = false
log4j.appender.FILE.layout=${log.patternLayout}
log4j.appender.FILE.layout.ConversionPattern=${log.pattern}

# BackUP files for every Day.
log4j.appender.FILE_PER_DAY=org.apache.log4j.DailyRollingFileAppender
# [[ Current File ] - logRollingDayFile.log ], { [BackUPs] logRollingDayFile.log_2017-12-10, ... }
log4j.appender.FILE_PER_DAY.File=${log.path}/logRollingDayFile.log
log4j.appender.FILE_PER_DAY.DatePattern='_'yyyy-MM-dd
log4j.appender.FILE_PER_DAY.layout=${log.patternLayout}
log4j.appender.FILE_PER_DAY.layout.ConversionPattern=${log.pattern}

# BackUP files for size rotation with log cleanup.
log4j.appender.FILE_PER_SIZE=org.apache.log4j.RollingFileAppender
# [[ Current File ] - logRollingFile.log ], { [BackUPs] logRollingFile.log.1, logRollingFile.log.2}
log4j.appender.FILE_PER_SIZE.File=${log.path}/logRollingFile.log
log4j.appender.FILE_PER_SIZE.MaxFileSize=100KB
log4j.appender.FILE_PER_SIZE.MaxBackupIndex=2
log4j.appender.FILE_PER_SIZE.layout=${log.patternLayout}
log4j.appender.FILE_PER_SIZE.layout.ConversionPattern=${log.pattern}

# MySql Database - JDBCAppender
log4j.appender.MySql=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.MySql.driver=com.mysql.jdbc.Driver
log4j.appender.MySql.URL=jdbc:mysql://localhost:3306/automationlab
log4j.appender.MySql.user=root
log4j.appender.MySql.password=
log4j.appender.MySql.layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.MySql.layout.ConversionPattern=INSERT INTO `logdata` VALUES ('%p', '%d{yyyy-MM-dd HH:mm:ss}', '%C', '%M', '%L', '%m');
#log4j.appender.MySql.sql=INSERT INTO `logdata` VALUES ('%p', '%d{yyyy-MM-dd HH:mm:ss}', '%C', '%M', '%L', '%m');

# Direct log events[Messages] to MongoDB Collection - MongoDbAppender
log.mongoDB.hostname=loalhost
log.mongoDB.userName=Yash777
log.mongoDB.password=Yash@123
log.mongoDB.DB=MyLogDB
log.mongoDB.Collection=Logs

log4j.appender.MongoDB=org.log4mongo.MongoDbAppender
log4j.appender.MongoDB.hostname=${log.mongoDB.hostname}
log4j.appender.MongoDB.userName=${log.mongoDB.userName}
log4j.appender.MongoDB.password=${log.mongoDB.password}
log4j.appender.MongoDB.port=27017
log4j.appender.MongoDB.databaseName=${log.mongoDB.DB}
log4j.appender.MongoDB.collectionName=${log.mongoDB.Collection}
log4j.appender.MongoDB.writeConcern=FSYNCED

MySQL表logdata的表结构

CREATE TABLE IF NOT EXISTS `logdata` (
  `Logger_Level` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `DataTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ClassName` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `MethodName` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `LineNumber` int(10) NOT NULL,
  `Message` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

log4j_External.xml«XML log4j:配置公共DTD文件

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration debug="false">

    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" />
        </layout>
    </appender>

    <appender name="FILE" class="org.apache.log4j.FileAppender">
        <param name="file" value="E:/Logs/logFile.log" />
        <param name="append" value="false" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" />
        </layout>
    </appender>

    <appender name="FILE_PER_SIZE" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="E:/Logs/logRollingFile.log" />
        <param name="immediateFlush" value="true"/>
        <param name="maxFileSize" value="100KB" />
        <param name="maxBackupIndex" value="2"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" />
        </layout>
    </appender>

    <appender name="FILE_PER_DAY" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="file" value="E:/Logs/logRollingDayFile.log" />
        <param name="datePattern" value="'_'yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n"/>
        </layout>
    </appender>

    <root>
        <priority value="info" />
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
        <appender-ref ref="FILE_PER_SIZE" />
        <appender-ref ref="FILE_PER_DAY" />
    </root>
</log4j:configuration>

Log4j配置从URL在Java程序: 为了使用外部文件指定自定义配置,所使用的类必须实现Configurator接口。 当默认配置文件“log4j. exe”时。属性”、“log4j.xml”不可用 “log4j。你可以把它提供给propertyconfiguration .configure(java.net.URL)方法。 对于“log4j.xml”,将使用DOMConfigurator。

public class LogFiles {
    // Define a static logger variable so that it references the Logger instance named "LogFiles".
    static final Logger log = Logger.getLogger( LogFiles.class );

    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        System.out.println("CONFIGURATION_FILE « "+LogManager.DEFAULT_CONFIGURATION_FILE);
        System.out.println("DEFAULT_XML_CONFIGURATION_FILE = 'log4j.xml' « Default access modifier");

        String fileName = //"";
                //"log4j_External.xml";
                "log4j_External.properties";
        String configurationFile = System.getProperty("user.dir")+"/src/" + fileName;

        if( fileName.contains(".xml") ) {
            DOMConfigurator.configure( configurationFile );
            log.info("Extension *.xml");
        } else if ( fileName.contains(".properties") ) {
            PropertyConfigurator.configure( configurationFile );
            log.info("Extension *.properties");
        } else {
            DailyRollingFileAppender dailyRollingAppender = new DailyRollingFileAppender();
            dailyRollingAppender.setFile("E:/Logs/logRollingDayFile.log");
            dailyRollingAppender.setDatePattern("'_'yyyy-MM-dd");

            PatternLayout layout = new PatternLayout();
            layout.setConversionPattern( "%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" );
            dailyRollingAppender.setLayout(layout);

            dailyRollingAppender.activateOptions();

            Logger rootLogger = Logger.getRootLogger();
            rootLogger.setLevel(Level.DEBUG);
            rootLogger.addAppender(dailyRollingAppender);

            log.info("Configuring from Java Class.");
        }

        log.info("Console.Message.");
        method2();
        methodException(0);
    }

    static void method2() {
        log.info("method2 - Console.Message.");
    }
    static void methodException(int b) {
        try {
            int a = 10/b;
            System.out.println("Result : "+ a);
            log.info("Result : "+ a);
        } catch (Exception ex) { // ArithmeticException: / by zero
            log.error(String.format("\n\tException occurred: %s", stackTraceToString(ex)));
        }
    }
    public static String stackTraceToString(Exception ex) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        return sw.toString();
    }
}