java logging api_Java Logging API - Tutorial

1.2. 創建一個logger

包 java.util.logging提供了日志的功能,可以使用類似于下面的代碼來創建一個logger:

import java.util.logging.Logger;

private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());

1.3.?Level

Log的等級反映了問題的嚴重程度。Level類用于決定哪些信息被寫入到log中。下面是一個按嚴重程度的降序排列的Log Level:

SEVERE (highest)

WARNING

INFO

CONFIG

FINE

FINER

FINEST

除此之外,您還可以使用OFF或ALL這兩個level來關閉log或打開所有log。

下面這行代碼是將logger設置為記錄INFO級別:

LOGGER.setLevel(Level.INFO);

1.4.?Handler

每個logger可以設置多個Handler。

Handler的作用是接收logger的信息,并將其以合適的格式發送到合適的地方。

一個Handler可以用setLevel(Level.OFF)來關閉,用setLevel(...)開啟。

JDK提供了幾個標準的handler,例如:

ConsoleHandler: 將log信息寫到Console

FileHandler: 將log信息寫到文件中

超過INFO(包含INFO)的信息將自動被寫入到Console中。

1.5.?Formatter

每個Handler的輸出都可以使用一個formatter來配置

已有的formatter:

SimpleFormatter 將所有的log信息以文本格式編排

XMLFormatter 生成XML格式的log信息

您還可以自定義Formatter,下面的這個示例Formatter可以將log信息用html的格式包裝:

package logging;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.logging.Formatter;

import java.util.logging.Handler;

import java.util.logging.Level;

import java.util.logging.LogRecord;

//This custom formatter formats parts of a log record to a single line

class MyHtmlFormatter extends Formatter

{

// This method is called for every log records

public String format(LogRecord rec)

{

StringBuffer buf = new StringBuffer(1000);

// Bold any levels >= WARNING

buf.append("

");

buf.append("

");

if (rec.getLevel().intValue() >= Level.WARNING.intValue())

{

buf.append("");

buf.append(rec.getLevel());

buf.append("");

} else

{

buf.append(rec.getLevel());

}

buf.append("

");

buf.append("

");

buf.append(calcDate(rec.getMillis()));

buf.append(' ');

buf.append(formatMessage(rec));

buf.append('\n');

buf.append("

");

buf.append("

\n");

return buf.toString();

}

private String calcDate(long millisecs)

{

SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");

Date resultdate = new Date(millisecs);

return date_format.format(resultdate);

}

// This method is called just after the handler using this

// formatter is created

public String getHead(Handler h)

{

return "\n

\n" + (new Date()) + "\n\n\n
\n"

+ "

+ "

TimeLog Message\n";

}

// This method is called just after the handler using this

// formatter is closed

public String getTail(Handler h)

{

return "

\n \n\n";

}

}

1.6.?Log Manager

log manager的職責是創建和管理logger,并負責維護log配置。

使用LogManager.setLevel(String name, Level level)方法,我們可以為一個包或一組包設置logging level。例如,我們可以將所有logger的logging

level設為Level.FINE:

LogManager.getLogManager().setLevel("logging", Level.FINE)

1.7.?Best Practices

使用被logged的那個類的名稱為logger命名是一種很好的方法,這種方法可以使程序員更好地查看日志和管理logger,同時,這也是Logging API推薦的一種方式。

2. 示例

您可以在項目“de.vogella.logger”中找到這個例子:

創建你自己的formatter:

package logging;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.logging.Formatter;

import java.util.logging.Handler;

import java.util.logging.Level;

import java.util.logging.LogRecord;

//This custom formatter formats parts of a log record to a single line

class MyHtmlFormatter extends Formatter

{

// This method is called for every log records

public String format(LogRecord rec)

{

StringBuffer buf = new StringBuffer(1000);

// Bold any levels >= WARNING

buf.append("

");

buf.append("

");

if (rec.getLevel().intValue() >= Level.WARNING.intValue())

{

buf.append("");

buf.append(rec.getLevel());

buf.append("");

} else

{

buf.append(rec.getLevel());

}

buf.append("

");

buf.append("

");

buf.append(calcDate(rec.getMillis()));

buf.append(' ');

buf.append(formatMessage(rec));

buf.append('\n');

buf.append("

");

buf.append("

\n");

return buf.toString();

}

private String calcDate(long millisecs)

{

SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");

Date resultdate = new Date(millisecs);

return date_format.format(resultdate);

}

// This method is called just after the handler using this

// formatter is created

public String getHead(Handler h)

{

return "\n

\n" + (new Date()) + "\n\n\n
\n"

+ "

+ "

TimeLog Message\n";

}

// This method is called just after the handler using this

// formatter is closed

public String getTail(Handler h)

{

return "

\n \n\n";

}

}初始化logger

package logging;

import java.io.IOException;

import java.util.logging.FileHandler;

import java.util.logging.Formatter;

import java.util.logging.Level;

import java.util.logging.Logger;

import java.util.logging.SimpleFormatter;

public class MyLogger {

static private FileHandler fileTxt;

static private SimpleFormatter formatterTxt;

static private FileHandler fileHTML;

static private Formatter formatterHTML;

static public void setup() throws IOException {

// Create Logger

Logger logger = Logger.getLogger("");

logger.setLevel(Level.INFO);

fileTxt = new FileHandler("Logging.txt");

fileHTML = new FileHandler("Logging.html");

// Create txt Formatter

formatterTxt = new SimpleFormatter();

fileTxt.setFormatter(formatterTxt);

logger.addHandler(fileTxt);

// Create HTML Formatter

formatterHTML = new MyHtmlFormatter();

fileHTML.setFormatter(formatterHTML);

logger.addHandler(fileHTML);

}

}使用logger

package logging;

import java.io.IOException;

import java.util.logging.Level;

import java.util.logging.Logger;

public class UseLogger {

// Always use the classname, this way you can refactor

private final static Logger LOGGER = Logger.getLogger(UseLogger.class

.getName());

public void writeLog() {

// Set the LogLevel to Severe, only severe Messages will be written

LOGGER.setLevel(Level.SEVERE);

LOGGER.severe("Info Log");

LOGGER.warning("Info Log");

LOGGER.info("Info Log");

LOGGER.finest("Really not important");

// Set the LogLevel to Info, severe, warning and info will be written

// Finest is still not written

LOGGER.setLevel(Level.INFO);

LOGGER.severe("Info Log");

LOGGER.warning("Info Log");

LOGGER.info("Info Log");

LOGGER.finest("Really not important");

}

public static void main(String[] args) {

UseLogger logger = new UseLogger();

try {

MyLogger.setup();

} catch (IOException e) {

e.printStackTrace();

throw new RuntimeException("Problems with creating the log files");

}

logger.writeLog();

}

}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273129.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273129.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273129.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

內存查看工具RAMMAP說明

參考 Technet Process Private: 分配給單一Process專用的內存 Mapped File: 用來儲放檔案內容快取(Cache)的內存空間 Shared Memory: 標注給多個Process共用的內存分頁(Page,內存管理單位) Page Table: 用來描述虛擬內存位址的分頁表(裡面是一筆一筆的PTE&…

php接口和java接口_java和php接口的區別是什么

java和php接口的區別是:1、php接口中的抽象方法只能是public的,默認也是public權限;2、java中私有方法使用private修飾,供接口中的默認方法或者靜態方法調用。【相關學習推薦:php編程(視頻)】php:規范:接口…

成都優步uber司機第四組獎勵政策

萬能的優步成都團隊放出了優步司機第四組,一二三組獎勵已經驟降,在月末放出第四組車主檔,這是要讓一切歸于平靜的節奏么!!! 滴滴快車單單2.5倍,注冊地址:http://www.udache.com/如何…

java hql多條件查詢_使用hql語句怎樣實現多條件查詢

展開全部這里只寫了DAO和業務62616964757a686964616fe59b9ee7ad9431333264623331邏輯組件、ACTION的具體實現類,PO和和接口自己應該會寫吧,HQL采用的是結合SQL的那種寫法,增刪改查全在里面了,修改下馬上就能跑了,不清楚…

BZOJ 1008 [HNOI2008]越獄

1008: [HNOI2008]越獄 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 5166 Solved: 2242[Submit][Status][Discuss]Description 監獄有連續編號為1...N的N個房間,每個房間關押一個犯人,有M種宗教,每個犯人可能信仰其中一種。如果相鄰房間…

android mysql開發工具_Android開發工具--adb的使用

adb(Android Debug Bridge)是Android提供的一個通用的調試工具,借助這個工具,我們可以管理設備或手機模擬器的狀態。還可以進行以下的操作:1、快速更新設備或手機模擬器中的代碼,如應用或Android系統升級;2、在設備上運…

java headless_使用Chrome Headless 快速實現java版數據的抓取

Java: cdp4j - Java library for CDP,使用這個類庫實現。maven引入:io.webfoldercdp4j1.1.0官方例子:import io.webfolder.cdp.Launcher;import io.webfolder.cdp.session.Session;import io.webfolder.cdp.session.SessionFactory;public class HelloWo…

閃回數據庫

Flashbacking a database means going back to a previous database state.閃回數據庫到之前數據庫的狀態The Flashback Database feature provides a way to quickly revert entire Oracle database to the state it was in at a past point in time. 閃回數據庫特性提供了一種…

Ruby on Rails Tutorial 第六章 用戶模型

1、用戶模型(1)數據庫遷移Rails默認使用關系數據庫存儲數據,數據庫中的表有數據行組成,每一行都有相應的列,對應數據屬性。把列名命名為相應的名字后,ActiveRecord會自動把他們識別為用戶對象的屬性。 $ ra…

java dcl 失效解決_DCL失效原因和解決方案

Java內存模型 在了解Java的同步秘密之前,先來看看JMM(Java Memory Model)。Java被設計為跨平臺的語言,在內存管理上,顯然也要有一個統一的模型。而且Java語言最大的特點就是廢除了指針,把程序員從痛苦中解脫出來,不…

李寧-2015年7月13日-個人文檔

姓名 李寧 日期 2015年7月13日 主要工作及心得 由于我負責服務器端的編寫工作,而各部分的客戶端的操作都要與服務器端通信,所以在今天的調試中,我貫穿于各部分模塊的調試和檢測,主要負責在出現問題…

java.net.unknown_android -------- java.net.UnknownServiceException

最近升級了Android的API版本時 ,導致我的網絡請求失敗了,出現了這個錯誤 java.net.UnknownServiceException,這個錯誤,我在網上查到這個主要是由于,我們的OkHttp3會默認使用密文傳輸,而我們的代碼中使用Htt…

無憂開通了博客園博客主頁

無憂開通了博客園博客主頁,今后在這里安家了。 分享一點工作經驗和學習心得,有事沒事常來看看。另一個獨立博客www.wuyouseo.com 轉載于:https://www.cnblogs.com/wuyoublog/p/4646481.html

pythonif語句的多分支使用_Python多分支if語句的使用

注意:if語句代碼是從上往下執行的,當執行到滿足條件的語句時,代碼會停止往下執行注意:if語句后面要加上冒號score int (input("score:"))if score > 90:print("A")elif score > 80:print(&…

Visual Studio下Qt調用IDL

一.簡單介紹: 1.ActiveQt包含QAxContainer和QAxServer組件。 1) QAxContainer允許使用COM對象,并且可以將ActiveX控件嵌入到Qt程序中去。 QAxContainer是有三個類組成的。分別是: QAxObject封裝了COM對象 QAxWidget封裝了ActiveX控…

安裝java過程_Java的安裝過程

記錄一下自己在Windowns下安裝java的過程打開網址后要先登錄,如果沒有號就先注冊,然后才能下載step1:下載JDK(1)將鼠標指向download,會出現如下界面:(2)點擊左上角PopularDownloads下的 Java for Developers進入如下界面&#xff…

HDU2571

早期昨晚,跪,體倦,簡直太CF該。早上起來刷標題。Then,寫python,shell,一天后基礎。 標題或標題中國~!思維:本主題開始尋找一個dfs,但是,這個矩陣外觀似太大,d…

dockerfile源碼安裝mysql_docker容器詳解五: dockerfile實現tomcat環境以及源碼安裝mysql...

tomcat上一節講到了dockerfile的基礎,這一次咱們來作一個小的練習首先要了解tomcat安裝的整個過程首先搭建 jdk環境:下載jdk包,解壓以后添加環境變量而后搭建tomcat:下載tomcat包,解壓,修改配置文件到一個工…

pom.xml的配置詳解

<!--可以免費轉載&#xff0c;轉載時請注明出處 http://pengqb.iteye.com 。--><project xmlns"http://maven.apache.org/POM/4.0.0 " xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance " xsi:schemaLocation"http://maven.apache.or…

azkaban 與 java任務_azkaban任務報錯java.lang.RuntimeException: The root scratch dir: /tmp/hive...

azkaban運行任務的時候失敗報錯如下&#xff1a;23-03-2016 08:16:14 CST analyzer-kafka2hdfs_new ERROR - Exception in thread "main" org.apache.hive.service.cli.HiveSQLException: java.lang.RuntimeException: The root scratch dir: /tmp/hive on HDFS shou…