0

我正在尝试在项目中使用 log4j2 进行日志记录。我的名为 log4j2.xml 的 conf 文件直接位于 java 项目下,并且我在类路径中有必要的 jar。当我使用下面的 conf 文件测试日志记录是否正常工作时,我只看到错误消息,尽管我也希望看到信息消息。有人知道这里有什么问题吗?

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <properties>
        <property name="servicename">m2mp_checker</property>
        <property name="patternTime">%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5.5p | %-10.10t | %-20.20C:%-5.5L | %msg%n</property>
        <property name="patternNoTime">%-5.5p | %-10.10t | %-20.20C:%-5.5L | %msg%n</property>
    </properties>
    <appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${patternTime}"/>
        </Console>
    </appenders>
    <loggers>
        <root level="INFO">
            <appender-ref ref="console"/>
        </root>
    </loggers>
</configuration>

爪哇代码:

package test;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.jcraft.jsch.*;

/**
 * @author : T12888
 */
public class Tester {
    private static final Logger logger = LogManager.getLogger(Tester.class);

    public static void main(String[] args) {

        String username = "aa";
        String host = "aa";
        String pass = "aa";
        String khfile = "/home/testuser/.ssh/known_hosts";
        String identityfile = "/home/testuser/.ssh/id_rsa";

        JSch jsch = null;
        Session session = null;
        Channel channel = null;
        ChannelSftp c = null;

        try {

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");

            jsch = new JSch();
            session = jsch.getSession(username, host, 22);
            session.setPassword(pass);
            session.setConfig(config);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();
            c = (ChannelSftp) channel;

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            logger.info("info");
            String fsrc = "abc.xml", fdest = "abc.xml";
            c.put(fsrc, fdest);
            c.get(fdest, "/tmp/testfile.bin");
        } catch (Exception e) {
            logger.error("error");
            e.printStackTrace();
        }
        finally{
            c.disconnect();
            session.disconnect();
        }
    }
}

输出:

11:27:45.873 [main] ERROR test.Tester - error
4

2 回答 2

0

终于解决了。问题是 log4j 没有加载我的配置文件(log4j2.xml)并使用默认配置将记录器设置为我猜的错误级别。感谢您的回复。

于 2013-05-15T10:46:18.973 回答
0

我想你忘记设置${patternTime}

像这样设置它:System.setProperty("patternTime", Your_PatternTime);

于 2013-05-15T09:04:59.507 回答