Log4j的使用(自定义Log4j工具)

Log4j的简介

log4j是Apache的一个开放源代码的项目,通过使用log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

此外,通过log4j其他的语言接口,您可以在C、C++、.Net、PL/SQL程序中使用log4j,其语法和用法与在Java程序中一样,使得多语言分布式系统得到一个统一一致的日志组件模块。而且,通过使用各种第三方扩展,您可以很方便地将Log4j集成到J2EE、JINI甚至是SNMP应用中。

2 、记录日志信息的作用?

1)监视代码中变量的变化情况,周期性的记录到文件中供其他应用进行统计分析工作;

​ 2)跟踪代码运行时轨迹,作为日后审计的依据;

​ 3)担当集成开发环境中的调试器的作用,向文件或控制台打印代码的调试信息。

使用Log4j框架的作用通俗的解释:

  • 能够控制日志信息想往哪里打就往哪里打,比如:控制台、文件、邮箱、数据库等等。
  • 能够控制日志信息想怎么打就怎么打,比如:我想要打印时间、程序的名称、程序的方法名、程序的行号、线程的名称等等。
  • 能够控制日志信息想打什么打什么,不想打的就不打,日志信息是分级别的,有时候我只想看错误的信息或者警告的信息,有时候我想看到所有的信息我想调试程序等等。

一 为什么要用log4j?

通常,我们写代码的过程中,免不了要输出各种调试信息。在没有使用任何日志工具之前,都会使用 System.out.println 来做到。 这么做直观有效,但是有一系列的缺点:

  1. 不知道这句话是在哪个类,哪个线程里出来的。

  2. 不知道什么时候前后两句输出间隔了多少时间。

  3. 无法关闭调试信息,一旦System.out.println多了之后,到处都是输出,增加定位自己需要信息的难度。等等

自定义Log4j工具

自定义配置文件

#定义我的Log4j信息
### 配置是否要输出到文件、控制台(1代表输出、0代表不输出)
isConsole = 0
isFile = 1

### 配置是否要输出debug、error(1代表输出、0代表不输出)
isDebug = 1
isError = 1

### 配置输出的文件的保存路径
debugPath = Logs/Debug/debug.log
errorPath = Logs/Error/error.log


### 配置日期滚动
isRole = 1

配置Log4j工具

package 日志使用.我的Log4j工具;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Properties;

public class wswLog4j {

	private static String isConsole;
	private static String isFile;
	private static String isDebug;
	private static String isError;
	private static String debugPath;
	private static String errorPath;
	private static String isRole;

	// 静态块(只会执行一次!!!)
	static {

		try {
			// 加载属性文件的内容到prop对象
			Properties prop = new Properties();
			prop.load(new FileInputStream("src/WswLog4j.properties"));

			// 取出prop对象中的每一个属性
			isConsole = prop.getProperty("isConsole");
			isFile = prop.getProperty("isFile");
			isDebug = prop.getProperty("isDebug");
			isError = prop.getProperty("isError");
			debugPath = prop.getProperty("debugPath");
			errorPath = prop.getProperty("errorPath");
			isRole = prop.getProperty("isRole");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 输出普通日志
	 */
	public static void debug(Object obj) {
		if ("1".equals(isDebug)) {
			String message = "[DEBUG] " + nowDate("yyyy-MM-dd HH:mm:ss,SSS");
			// 方法运行栈信息(能够定位在某个java文件的第几行)
			StackTraceElement[] array = Thread.currentThread().getStackTrace();
			/*
			 * 0 at java.io.FileInputStream.open0(Native Method) 1 at
			 * java.io.FileInputStream.open(FileInputStream.java:195) 2 at
			 * java.io.FileInputStream.<init>(FileInputStream.java:138) 3 at
			 * java.io.FileInputStream.<init>(FileInputStream.java:93) 4 at
			 * log4j.Test.main(Test.java:20)
			 */
			// for (StackTraceElement stackTraceElement : array) {
			// System.out.println(stackTraceElement);
			// }
			// 我们要的就是调用debug()方法的这一处运行栈信息
			message += " " + array[2].toString();
			// 拼接日志的内容
			message += obj.toString() + "\r\n";

			// 打印到控制台
			if ("1".equals(isConsole)) {
				System.out.print(message);
			}

			// 写出到文件
			if ("1".equals(isFile)) {
				if ("1".equals(isRole)) {
					writeFile(debugPath, message);
				} else {
					writeFile(debugPath, message);
				}
			}
		}
	}

	/**
	 * 输出错误日志
	 */
	public static void error(Exception exception) {
		if ("1".equals(isError)) {
			String message = "[ERROR] " + nowDate("yyyy-MM-dd HH:mm:ss,SSS");
			// 获取引发异常对象的 运行栈数组
			StackTraceElement[] array = Thread.currentThread().getStackTrace();
			message += " " + array[2].toString();
			// 拼接日志的内容
			message += exception.toString() + "\r\n";
			// 拼接 引发异常的运行栈数组
			StackTraceElement[] exceptionArray = exception.getStackTrace();
			for (StackTraceElement e : exceptionArray) {
				message += "\t" + e.toString() + "\r\n";
			}

			// 输出到控制台
			if ("1".equals(isConsole)) {
				System.err.print(message);
			}

			// 输出到文件
			if ("1".equals(isFile)) {
				if ("1".equals(isRole)) {
					writeFile(errorPath, message);
				} else {
					writeFile(errorPath, message);
				}
			}
		}
	}

	/*
	 * 获取当前时间
	 */
	private static String nowDate(String format) {
		// 获取当前时间
		Date date = new Date();
		// 定义时间格式模板
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		// 应用模板
		String str = sdf.format(date);
		return str;
	}

	private static void writeFile(String filePath, String message) {
		Writer writer = null;
		try {
			File file = new File(filePath);
			if (!file.exists()) {// 如果不存在,则创建之
				// file.mkdirs();
				// 给该文件所在父级目录 逐级创建
				file.getParentFile().mkdirs();
			}

			writer = new FileWriter(file, true);

			writer.write(message);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static void rollDate(String filePath, String message) {
		Writer writer = null;
		try {
			String nowDateStr = nowDate("yyyy-MM-dd");

			filePath = filePath + "--" + nowDateStr;

			File file = new File(filePath);
			if (!file.exists()) {// 如果不存在,则创建之
				// file.mkdirs();
				// 给该文件所在父级目录 逐级创建
				file.getParentFile().mkdirs();
			}

			writer = new FileWriter(file, true);

			writer.write(message);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

定义测试类

package 日志使用.我的Log4j工具;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import 日志使用.自定义Log4j工具.WsdLog4j;

public class wswTest {
public static void main(String[] args) {
	try {
		wswLog4j.debug("啊啊啊啊");
		wswLog4j.debug("哦哦哦哦哦");
		wswLog4j.debug("鹅鹅鹅鹅鹅");
		

		InputStream input = new FileInputStream("/Users/wushiwei/文件/asdasdsaddt.txt");

	} catch (FileNotFoundException e) {
		
		wswLog4j.error(e);
	}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Micek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值