昨天用Log4J2写了一个示例程序,详见《一个简单的Log4J2示例程序》:
今天我尝试用Log4J写一个示例程序。Jar包下载地址如下:
这个压缩包解压缩后,里面只有一个jar包log4j-1.2.17.jar,将这个jar包导入Java项目即可使用Log4J
现有一个配置文件log4j.properties内容如下:
# 日志等级 # log4j.rootLogger = DEBUG, Console, LogFile # 打印日志到控制台 # log4j.appender.Console = org.apache.log4j.ConsoleAppender log4j.appender.Console.Target = System.out log4j.appender.Console.ImmediateFlush = true log4j.appender.Console.Threshold = DEBUG log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern = [%-d{yyyy-MM-dd HH:mm:ss}] [%t] %l %n[%p] %m%n%n # 保存日志文件 #log4j.appender.LogFile = org.apache.log4j.RollingFileAppender# 防止输出中文时出现乱码,加上Encoding配置 #log4j.appender.LogFile.Encoding=GBKlog4j.appender.LogFile.File = logs/log_data.log log4j.appender.LogFile.Append = true log4j.appender.LogFile.ImmediateFlush = true log4j.appender.LogFile.MaxFileSize = 8MB log4j.appender.LogFile.MaxBackupIndex = 256 log4j.appender.LogFile.Threshold = INFO log4j.appender.LogFile.layout = org.apache.log4j.PatternLayout log4j.appender.LogFile.layout.ConversionPattern = [%-d{yyyy-MM-dd HH:mm:ss}] [%t] %l %n[%p] %m%n%n
注意如果需要对外输出到文件,一定要设置Encoding,否则输出到日志文件中的汉字会变为乱码
Java代码如下:
import java.io.PrintWriter;import java.io.StringWriter;import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;public class Log4JTest { public static void main(String[] args) { try { //读取配置 String propertiesFilePath = "C:\\Users\\Tsybius\\Desktop\\log4j.properties"; PropertyConfigurator.configure(propertiesFilePath); //建立Logger Logger logger = Logger.getLogger(Log4JTest.class); //写日志 logger.debug("日志级别:DEBUG"); logger.info("日志级别:INFO"); logger.warn("日志级别:WARN"); logger.error("日志级别:ERROR"); logger.fatal("日志级别:FATAL"); } catch (Exception ex) { //打印异常 StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ex.printStackTrace(printWriter); System.out.println(stringWriter.toString()); } }}
打印到控制台的日志如下:
打印到文件的日志如下:
END