JDK Logger使用舉例

來源:互聯網
上載者:User

在一些場合無需引入log4j等第三方日誌庫,例如編寫FileNet component時可能只需要簡單的日誌記錄,同時又不能使用設定檔,則直接利用JDK提供的Logger即可。使用它首先根據自己的需要編寫一個輸出資訊格式化類,在使用Logger時先設定log記錄位置,設定log檔案增長命名方式,設定logger處理層級,設定格式化類等等即可進行使用,具體方式如下代碼所示。

 

import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger;public class LoggerTest {private static final Logger logger =  Logger.getLogger(LoggerTest.class.toString());public static void main(String[] args) { //設定logger資訊FileHandler fileHandler;try {fileHandler = new FileHandler("c:/dataMigration%g.log", 256000,1000000, true);fileHandler.setLevel(Level.ALL);fileHandler.setFormatter(new MyLogHander());logger.addHandler(fileHandler);logger.setLevel(Level.ALL);} catch (SecurityException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}logger.info("test logger info");}}class MyLogHander extends Formatter {@Overridepublic String format(LogRecord record) {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");return sdf.format(date) + "  " +  record.getLevel() + ":    " + record.getMessage() + "\r\n";}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.