在项目的开发过程中,往往需要使用日志的功能,不仅便于调试,更是为了以后问题的排查。本文是一个简单的log4j的示例。
环境
语言:scala
IDE :Intellij IDEA
log4j.properties 文件
这个文件放在resources目录下
将日志以控制台方式输出,日志级别为INFO
log4j.properties内容如下:
log4j.rootLogger=INFO,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p\t%d{ISO8601}\t%r\t%c\t[%t]\t%m%n
输出结果:
INFO 2017-01-19 15:57:03,957 0 TestLogger [main] This is info ...
WARN 2017-01-19 15:57:03,957 0 TestLogger [main] This is info ...
ERROR 2017-01-19 15:57:03,957 0 TestLogger [main] This is error ...
将日志以控制台方式输出及输出到日志文件,日志级别为INFO
log4j.properties内容如下:
# initialize root logger with level ERROR for stdout and fout
log4j.rootLogger=INFO,stdout,fout
# add a ConsoleAppender to the logger stdout to write to the console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# use a simple message format
log4j.appender.stdout.layout.ConversionPattern=%m%n
# add a FileAppender to the logger fout
log4j.appender.fout=org.apache.log4j.FileAppender
# create a log file
log4j.appender.fout.File=test.log
log4j.appender.fout.layout=org.apache.log4j.PatternLayout
# use a more detailed message pattern
log4j.appender.fout.layout.ConversionPattern=%p\t%d{ISO8601}\t%r\t%c\t[%t]\t%m%n
输出结果:
这个日志不仅会在控制台输出,也会以文件test.log
的形式输出,这个文件的位置为以下:
[root@master Project]# find . -name test.log
./.idea/modules/test.log
除此之外,还有其他日志级别,如下:
- DEBUG designates fine-grained informational events that are most useful to debug a crawl configuration.
- TRACE designates fine-grained informational events than DEBUG.
- ERROR designates error events that might still allow the crawler to continue running.
- FATAL designates very severe error events that will presumably lead the crawler to abort.
- INFO designates informational messages that highlight the progress of the crawl at a coarse-grained level.
- OFF has the highest possible rank and is intended to turn off logging.
- WARN designates potentially harmful situations.
示例代码
import org.apache.log4j.{LogManager, Logger}
import org.junit.Test
/**
* Created by yang on 1/19/17.
*/
class TestLogger {
val LOGGER :Logger = LogManager.getLogger("TestLogger")
@Test
def testLoggerFunction(): Unit ={
LOGGER.info("This is info ...")
LOGGER.warn("This is warn ...")
LOGGER.error("This is error ...")
}
}
总结
当需要使用Log4j时,需要注意以下几点:
- 下载log4j库,不管是mavn也好,sbt也罢,或直接下载jar放到类目录也行,总之需要有库;
- 日志配置文件,不管是log4j.properties,还是log4j.xml,log4j2.xml,反正,一定要有配置文件;
- 配置文件所放的位置,必须要放到项目能够自动加载的目录,如类目录,如果使用了项目构建工具的话,可以放在resources目录下。如果放在系统找不到的目录下,会提示找不到log4j.xml
- 获取一个日志实例,然后就可以info, warn 和error等等了。。。
参考文献
[1] https://docs.oracle.com/cd/E29578_01/webhelp/cas_webcrawler/src/cwcg_config_log4j_file.html
其他相关资源:
https://www.mkyong.com/logging/log4j-log4j-properties-examples/