Logging in Java

不羁岁月 提交于 2019-12-05 21:39:33

You can either add handlers only for the wanted items, making your selection at logging start-up time; or, you can add all the handlers, and tune each Handler via logging thresholds.

To tune a Handler's logging threshold, use handler.setLevel(...);

Note that on start-up a default Handler is already configured. You might need to programmatically remove that handler, or tune it to handle nothing depending on which technique of log handler "handling" you wish to implement.

See the API documentation for that class: Logger (Java Platform SE 6).

You can remove handlers via the removeHandler(Handler) method, so if you want to only output to the console, for example, you can invoke this method to remove the FileHandler.

There are other ways as well. You could take a different approach and set filters for each handler, which would discard messages that are not supposed to be outputted. Maybe play around with the formatting.

You could have achieved desired configuration without even writing any code. Here is how: Browse to the directory where java is installed on your system.

  1. Go to the jre/lib (or jre\lib in windows) subdirectory,and look for the file "logging.properties". You can create it if it doesn't exist.

  2. Edit the line having content "handlers = " TO

    -For Both System.err and File

    "handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler"
    

    -For Neither System.err and File

    Simply comment that line by adding # in the beginning of the line.
    

    -For Just System.err

    "handlers = java.util.logging.ConsoleHandler"
    

    -For Just File

    "handlers = java.util.logging.FileHandler"
    

Done! You are good to go and start logging :)

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