import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
/**
* 可以自已定义日志打印格式,这样看起来比较方便些
*
*/
class MyFormatter extends Formatter
{
@Override
public String format(LogRecord arg0)
{
//创建StringBuilder对象来存放后续需要打印的日志内容
StringBuilder builder = new StringBuilder();
//获取时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date now = new Date();
String dateStr = simpleDateFormat.format(now);
builder.append("[");
builder.append(dateStr);
builder.append(" ");
//拼接日志级别
builder.append(arg0.getLevel()).append(" ");
builder.append(arg0.getSourceClassName()).append(" ");
//拼接方法名
//builder.append(arg0.getSourceMethodName()).append(" ");
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String line = stackTrace[8].toString();
for (int i = 0; i < stackTrace.length; i++) {
//System.out.println(stackTrace[i]);
}
//String lineNumber = line.substring(line.indexOf(":") + 1, line.length() - 1);
String lineNumber = line.substring(line.indexOf(":") + 1, line.length() - 1);
//拼接方法名
builder.append(line).append("] ");
//拼接日志内容
builder.append(arg0.getMessage());
//日志换行
builder.append("\r\n");
return builder.toString();
}
}
public class MyLogger {
static Logger logger;
static {
logger = Logger.getLogger(MyLogger.class.getName());
logger.setUseParentHandlers(false);
//如果需要将日志文件写到文件系统中,需要创建一个FileHandler对象
Handler consoleHandler = new ConsoleHandler();
//创建日志格式文件:本次采用自定义的Formatter
consoleHandler.setFormatter(new MyFormatter());
//将FileHandler对象添加到Logger对象中
logger.addHandler(consoleHandler);
}
public static Logger getLogger() {
return logger;
}
public static void main(String[] args) throws SecurityException, IOException {
Logger logger = Logger.getLogger(MyLogger.class.toString());
logger.info("123");
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
System.out.println(stackTrace.length);
for (StackTraceElement s: stackTrace) {
System.out.println(s.toString());
}
/*
Logger myLogger = MyLogger.getLogger();
myLogger.info("1123");
-----------------------------------
©著作权归作者所有:来自51CTO博客作者mob64ca12e86bd4的原创作品,请联系作者获取转载授权,否则将追究法律责任
java logger打印错误行号
https://blog.51cto.com/u_16213398/7623080
myLogger.info("11");*/
}
}
import java.util.logging.Logger;
public class CLASS_A {
Logger logger = MyLogger.getLogger();
void run()
{
logger.info("run");
}
public static void main(String[] args) {
CLASS_A a = new CLASS_A();
a.run();
a.logger.info("11");
}
}