How to get java Logger output to file by default [duplicate]

こ雲淡風輕ζ 提交于 2019-11-27 10:08:30

问题


This question already has an answer here:

  • Where does java.util.logging.Logger store their log 3 answers

Netbeans thoughtfully sprinkles Logger.getLogger(this.getClass().getName()).log(Level. [...] statements into catch blocks. Now I would like to point them all to a file (and to console).

Every logging tutorial and such only me tells how to get a specific logger to output into a file, but I assume there is a better way than fixing every automatically generated logging statement? Setting a handler for some sort of root logger or something?


回答1:


I just add the following at startup

Handler handler = new FileHandler("test.log", LOG_SIZE, LOG_ROTATION_COUNT);
Logger.getLogger("").addHandler(handler);

You can specify your own values for LOG_SIZE and LOG_ROTATION_COUNT

You may need adjust the logging level to suit.




回答2:


You have to define where the log is writting in the logger configuration file. For example, if you use log4j, a log4j.xml (or log4j.properties) file will contain such information.

For example, here is a simple log4j.xml file that logs directly into a file (my-app.log) and in the console:

<?xml version="1.0" encoding="UTF-8"?>
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="rolling" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="my-app.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{yyyy-MM-dd HH:mm:ss} %-5p [%C] [IP=%X{ipAddress}] [user=%X{user}] %m%n" />
        </layout>
    </appender>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{yyyy-MM-dd HH:mm:ss} %-5p [%C] [user=%X{user}] %m%n" />
        </layout>
    </appender>

    <root>
        <priority value="info" />
        <appender-ref ref="console" />
        <appender-ref ref="rolling" />
    </root>

</log4j:configuration>


来源:https://stackoverflow.com/questions/751736/how-to-get-java-logger-output-to-file-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!