Java日志实战及解析

原创 2016年08月29日 10:07:37

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的一般ConsoleConsoleAppender)用来调试,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 specifyingAbsoluteTimeDateFormatDateTimeDateFormat 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

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

自己用java写了一款日志查找分析工具

工作中需要查日志,在日志中发现grep不能把一个时间戳中的内容都搜索到,因为grep只能按行读文件,于是自己写了一款查日志的工具,可以实现多文本、多正则表达式匹配文本并打印。源代码分享如下: /* ...

RecyclerView实现悬浮吸顶

使用RecyclerView实现悬浮吸顶效果

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

unity地形编辑扩展插件Landspace Auto Material介绍

LAM是一套针对复杂地形和植物的编辑工具, 增加了一些unity自带地形编辑器没有的功能, 对其用法做一下简单介绍。

关注CSDN程序人生公众号,轻松获得下载积分

关注公众号 在公众号里回复“”秘密“”两个字 返回 http://task.csdn.net/m/task/home?task_id=398 领取奖励 提示:根据公众号里的自动回复,完成...

Android设计模式学习之观察者模式

观察者模式在实际项目中使用的也是非常频繁的,它最常用的地方是GUI系统、订阅——发布系统等。因为这个模式的一个重要作用就是解耦,使得它们之间的依赖性更小,甚至做到毫无依赖。以GUI系统来说,应用的UI...

JavaEE 6及以上版本的web.xml问题?

JavaEE 6及以上版本的web.xml问题?MyEclipse JavaEE 6版本开始web.xml突然消失不见?没这回事,只是不太必须而已,有需要的项目可以自行进行添加或在创建项目的时候点击n...

面试题:8个试剂,其中一个有毒,最少多少只小白鼠能检测出有毒试剂

面试题:8个试剂,其中一个有毒,最少多少只小白鼠能检测出有毒试剂方法1:用3只小鼠,能组合成8种状态。 第一只喂食【1、3、5、7】四只试剂 第二只喂食【2、3、6、7】四只试剂 第三只喂食【4、5、...

感悟达人

在我们这个圈子里,有些话是不能明说的,在题目上更不感放肆,所以就用了达人来暗示一些人一直对于达人,都是很向往的,可以高扬着嗓子,可以威武着眼神,可以挥斥方求.可以视金钱如粪土,又可以满身粪土,满屋粪土...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)