使用Logger Java将日志写入.log / .txt文件

时间:2018-08-01 08:54:12

标签: java spring logging

我制作了一个日志记录系统,但是我需要将日志消息写入一个单独的log / txt文件中。

我想到了这个

public class UIRestService {

    private static final Logger LOGGER = Logger.getLogger(UIRestService.class.toString());

    FileHandler fh;

    public UIRestService() {
        try {
            fh = new FileHandler("E:/MyLog.log");
            LOGGER.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    public MainDTO registerEORI(@RequestBody EoriRegistration json){
        long startTime = System.currentTimeMillis();
        try {
            LOGGER.info("--- Start EORI registration ---");
            EoriData entity = Converter.convertDTO2Entity(json);
            LOGGER.info("Converted DTO to Entity");
            MainDTO dto = dataManager.registration(entity);
            if (dto instanceof EoriRegistration) {
                msgManager.writeMsg(json.getState(), json.getC8_number() == null ? "test" : json.getC8_number());//TODO remove after IAM json.getC8_number()
            }
            return dto;
        } catch (Exception e){
            LOGGER.info("Exception in registerEORI");
            e.printStackTrace();
            Error error = new Error(Constants.TYPE_DTO2);
            error.setErrorDescription(e.getMessage());
            LOGGER.info("Exception in registerEORI" + error);
            return error;
        } finally {
            long endTime = System.currentTimeMillis();
            LOGGER.info("Registering EORI id: " + json.getId() + " , eori number:" + json.getEoriNumber() + " , elapsed:" + (endTime - startTime));
        }
    }

}

我在E:/中手动创建了MyLog.log文件,但是没有任何内容。我尝试使用没有手动创建的文件-再次没有。它说从未使用过构造函数。你能告诉我我做错了什么吗?我使用了这个示例-Example

1 个答案:

答案 0 :(得分:0)

我认为您必须设置日志级别。

LOGGER.setLevel(Level.INFO)

我总是按照vogella.com(http://www.vogella.com/tutorials/Logging/article.html#logexample_createLogger)的教程对Logger进行初始化,并且它们可以正常工作:

    Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

    // suppress the logging output to the console
    Logger rootLogger = Logger.*getLogger*("");
    Handler[] handlers = rootLogger.getHandlers();
    if (handlers[0] instanceof ConsoleHandler) {
        rootLogger.removeHandler(handlers[0]);
    }

    logger.setLevel(Level.INFO);
    fileTxt = new FileHandler("Logging.txt");
    fileHTML = new FileHandler("Logging.html");

    // create a TXT formatter
    formatterTxt = new SimpleFormatter();
    fileTxt.setFormatter(formatterTxt);
    logger.addHandler(fileTxt);

(来源:http://www.vogella.com/tutorials/Logging/article.html#logexample_createLogger