slf4j+log4j 将log写入console及文件里

做个java小工具,麻雀虽小五脏俱全。日志系统还是要有的,一个好的程序媛在写代码时,一定要附上自己的log,这样方便自己,方便他人。Java以前用过log4j,但是最近看了不少帖子,都推荐使用slf4j门面模式。这个是sl4j 官网介绍

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks, such as java.util.logging, logback and log4j

maven project里的pom.xml 添加一下依赖:


	org.slf4j
	slf4j-log4j12
	1.8.0-beta4

然后是log4j的配合使用,在src/里添加上log4j.properties,以下是借鉴的。 其实,我们可以从每行等式左边的名称上可以看出用途。首先了解下log4j的log级别定义

Level Description
ALL All levels including custom levels.
DEBUG Designates fine-grained informational events that are most useful to debug an application.
INFO Designates informational messages that highlight the progress of the application at coarse-grained level.
WARN Designates potentially harmful situations.
ERROR Designates error events that might still allow the application to continue running.
FATAL Designates very severe error events that will presumably lead the application to abort.
OFF The highest possible rank and is intended to turn off logging.
TRACE Designates finer-grained informational events than the DEBUG.
log4j.rootLogger=DEBUG, STDOUT, file 将log级别高于Debug(含)的输出到屏幕与文件里。
log4j.appender.STDOUT* 定于输出到屏幕上的log信息
log4j.appender.file* 定义输出到文件里的log信息
log4j.rootLogger=DEBUG, STDOUT, file   

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=log/encryPassword.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n

然后代码中这样来使用就ok了。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
....

private final static Logger LOGGER = LoggerFactory.getLogger(YouClass.class);

private void chkFileExist() {
    if (pwFile.length() == 0 ) {
        LOGGER.warn("there is no pwencry for encryped.");
	System.exit(1);
    }


或者声明为这种类型
protected final Logger log = LoggerFactory.getLogger(getClass());

关于里面把Logger实例声明为final static类型,slf4j官网给了这个解释(https://www.slf4j.org/faq.html#declared_static)

In summary, declaring logger members as static variables requires less CPU time and have a slightly smaller memory footprint. On the other hand, declaring logger members as instance variables requires more CPU time and have a slightly higher memory overhead. However, instance variables make it possible to create a distinct logger environment for each application, even for loggers declared in shared libraries. Perhaps more important than previously mentioned considerations, instance variables are IOC-friendly whereas static variables are not.

声明为static,让Logger以类的变量存在,如果类被多次实例化,你们可以节省比较多的CPU时间片以及内存消耗。但是,如果把logger作为对象的属性,可以保持在多application的开发中,当类被多个application使用的时候,能够区分开各个application的上下文环境,这样可以区别到底是哪个application的log了。 那就用第二种声明方式比较合适了。所以这个需要应用到具体的开发中去。

 

未完待续

你可能感兴趣的:(java)