跟王老師學異常(八):開源日誌記錄工具log4j的使用案例

來源:互聯網
上載者:User

標籤:

開源日誌記錄工具log4j的使用主講人:王少華  QQ群號:483773664學習目標

掌握Log4J在java項目中的應用

一、日誌分類及log4j介紹(一)日誌及分類
1 日誌
  • 主要用來記錄系統運行中一些重要操作資訊

  • 便於監視系統運行情況,協助使用者提前發現和避開可能出現的問題,或者出現問題後根據日誌找到原因

2、分類
  • SQL日誌:記錄系統執行的SQL語句

  • 異常日誌:記錄系統運行中發生的例外狀況事件

  • 業務日誌:記錄系統運行過程。如使用者登入、操作記錄

(二)Log4j介紹

Log4j是Apache是一個開源項目。

控制日誌的輸出層級

控制日誌資訊輸送的目的地是控制台、檔案等

控制每一條日誌的輸出格式

官網:http://logging.apache.org/log4j/1.2/

這裡我們使用的版本是:1.2.17

二、使用Log4j記錄日誌(一)、在項目中加入log4j的JAR檔案
(二)、建立log4j.properties檔案(三)、配置日誌資訊
12345678910111213 ### 設定Logger輸出層級和輸出目的地 ###log4j.rootLogger=debug, stdout,logfile ### 把日誌資訊輸出到控制台 ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.SimpleLayout ### 把日誌資訊輸出到檔案:wangsh.log ###log4j.appender.logfile=org.apache.log4j.FileAppenderlog4j.appender.logfile.File=wangsh.loglog4j.appender.logfile.layout=org.apache.log4j.PatternLayoutlog4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss}%l %F %p %m%n

650) this.width=650;" border="0" src="http://s3.51cto.com/wyfs02/M00/7F/B3/wKioL1cprnHBVFpAAACX-4l8-G8116.png" data_ue_src="E:\My Knowledge\temp\8fe36664-4145-406c-ba1b-5e634ec76d45.png">

(四)、在程式中使用log4j
1234567891011121314151617181920212223242526 public class Test {    private static Logger logger = Logger.getLogger(Test.class.getName());    public static void main(String[] args) {        try {            Scanner in = new Scanner(System.in);            System.out.print("請輸入被除數:");            int num1 = in.nextInt();            logger.debug("輸入被除數:" + num1);            System.out.print("請輸入除數:");            int num2 = in.nextInt();            logger.debug("輸入除數:" + num2);            System.out.println(String.format("%d / %d = %d", num1, num2, num1                    / num2));            logger.debug("輸出運算結果:"                    + String.format("%d / %d = %d", num1, num2, num1 / num2));        } catch (InputMismatchException e) {            logger.error("被除數和除數必須是整數", e);        } catch (ArithmeticException e) {            logger.error(e.getMessage());        } catch (Exception e) {            logger.error(e.getMessage());        } finally {            System.out.println("歡迎使用本程式!");        }    }}








來自為知筆記(Wiz)

跟王老師學異常(八):開源日誌記錄工具log4j的使用案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.