Java日誌實戰及解析
日誌是程序員必須掌握的基礎技能之一,如果您寫的軟件沒有日誌,可以說你沒有成爲一個真正意義上的程序員。
爲什麼要記日誌?
• 監控代碼
• 變量變化情況,系統運行過程。
• 產線環境,不太好調試。
• 分佈式環境下,調試更困難,日誌就是非常好的幫手。
• 統計分析
• 日後審計
• 實際中有4%的代碼是日誌!
Java日誌框架主要有log4j,logback,及其他不常用的官方日誌及apachelogging等。
Log4j和LogBack的原作者爲同一作者CekiGülcü。主流使用的一般是log4j的居多點,所以本文主要也講解log4j爲主。
配置文件log4j.properites文件,一般放倒classpath目錄下即可,無需自啓。
log4j.rootLogger=debug, stdout,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%-4r[%t] %5p %c %x -%m - %X{userName}%n
log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%-4r[%t] %5p %c %x -%m - %X{userName}%n |
log4j.rootLogger=debug, stdout,R
log4j.rootLogger=[Level], Appender1, Appender2
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
其他類似
基本是三大主件的配置:
Logger
日誌類型和日誌級別(TRACE < DEBUG < INFO < WARN <ERROR < FATAL)
Appenders
輸出到哪裏,可以有多個目的地( Console,File,GUI 組件,remote socket servers,JMS,NT Event Loggers,remote Unix Syslog daemons。也可以異步)
Appenders的一般Console(ConsoleAppender)用來調試,File有每天更新(DailyRollingFileAppender)和最大多大文件(RollingFileAppender)滾動的設置,也有郵件的告警設置。基本理解上面的即可。
Layouts
%r [%t] %-5p %c - %m%n
176 [main] INFO org.foo.Bar - Located nearest gasstation.
Layouts說明
Conversion Character |
Effect |
c |
Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets. If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full. For example, for the category name "a.b.c" the pattern %c{2} will output "b.c". |
C |
Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets. If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form. For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass". WARNING Generating the caller class information is slow. Thus, use should be avoided unless execution speed is not an issue. |
d |
Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example,%d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed. The date format specifier admits the same syntax as the time pattern string of the SimpleDateFormat. Although part of the standard JDK, the performance ofSimpleDateFormat is quite poor. For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifyingAbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d{ISO8601} or %d{ABSOLUTE}. These dedicated date formatters perform significantly better than SimpleDateFormat. |
F |
Used to output the file name where the logging request was issued. WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue. |
l |
Used to output location information of the caller which generated the logging event. The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses. The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue. |
L |
Used to output the line number from where the logging request was issued. WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue. |
m |
Used to output the application supplied message associated with the logging event. |
M |
Used to output the method name where the logging request was issued. WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue. |
n |
Outputs the platform dependent line separator character or characters. This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator. |
p |
Used to output the priority of the logging event. |
r |
Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event. |
t |
Used to output the name of the thread that generated the logging event. |
x |
Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event. |
X |
Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output. See MDC class for more details. |
% |
The sequence %% outputs a single percent sign. |
更多說明:
Format modifier |
left justify |
minimum width |
maximum width |
comment |
%20c |
false |
20 |
none |
Left pad with spaces if the category name is less than 20 characters long. |
%-20c |
true |
20 |
none |
Right pad with spaces if the category name is less than 20 characters long. |
%.30c |
NA |
none |
30 |
Truncate from the beginning if the category name is longer than 30 characters. |
%20.30c |
false |
20 |
30 |
Left pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |
%-20.30c |
true |
20 |
30 |
Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |
Maven引用
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.8</version> </dependency> |
個人認爲必須瞭解和掌握的日誌特性:
日誌級別
繼承
JMX管理
Appenders的Additivity
其他的需要了解
Filter
NDC
MDC
日誌調優
示例: logger.debug(“Entry number: ” + i + “ is ” + String.valueOf(entry[i])); if(logger.isDebugEnabled() { logger.debug(“Entry number: ” + i + “ is ” + String.valueOf(entry[i])); } 判斷只是記錄日誌的1%時間,所以一般情況下是值得的。 但是一般使用SLF4J就自動集成該功能。 |
在瞭解Log4j之後,也必須瞭解一下SLF4j,大家一般是使用這個進行整合內部不同日誌的具體實現的。
Maven使用
• <dependency> • <groupId>org.slf4j</groupId> • <artifactId>slf4j-api</artifactId> • <version>1.7.21</version> • </dependency> |
• Logger logger = LoggerFactory.getLogger(HelloWorld.class); • logger.info("Hello World"); |
常用記錄日誌的地方:
• 方法入口
• 方法出口
• 異常
• 自己需要跟蹤的信息
• 距離日誌最近的地方記錄日誌
• 先記錄日誌,後拋異常,可以把異常往上拋
• 去除冗餘日誌
日誌庫的使用情況
日誌一般會使用即可。掌握本課程基本夠用,剩下來就看你自己了。
著名的solr使用日誌的情況
一般大企業,會收集日誌,使用ELK等技術查看日誌,或sink到hadoop進行數據分析和挖掘,甚至使用storm進行實時統計。
更多內容可以參考視頻:
CSDN學 院: http://edu.csdn.net/course/detail/2890
網易雲課堂: http://study.163.com/course/introduction/1003149011.htm