📅  最后修改于: 2023-12-03 14:42:49.510000             🧑  作者: Mango
LogRecord是Java日志框架中的一个类,用于描述一条日志记录。其中,getThreadID()是LogRecord类中获取日志记录线程ID的方法。
public int getThreadID()
无参
返回值类型为int,表示日志记录所在线程的ID。
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.LogRecord;
public class Demo {
private static Logger logger = LogManager.getLogger(Demo.class.getName());
public static void main(String[] args) {
Runnable r1 = new Runnable() {
@Override
public void run() {
logger.log(Level.INFO, "This message is from thread1.");
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
logger.log(Level.WARNING, "This message is from thread2.");
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.getHandlers()[0].setFormatter(new java.util.logging.SimpleFormatter() {
@Override
public String format(LogRecord record) {
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append(record.getLevel().getName());
builder.append("] ");
builder.append("[" + record.getThreadID() + "] ");
builder.append(formatMessage(record));
builder.append("\n");
return builder.toString();
}
});
logger.log(Level.INFO, "This message is from the main thread.");
}
}
该示例代码中,我们创建了两个线程t1和t2,并通过Runnable接口来定义它们的行为。在每个线程内,使用Logger记录了一条日志,其中利用了getThreadID()获取当前线程ID。最后,通过SimpleFormatter重写日志输出格式,将日志输出时增加线程ID。当主线程里记录了一条日志时,同样可以看到它的线程ID。
[INFO] [10] This message is from thread1.
[WARNING] [11] This message is from thread2.
[INFO] [1] This message is from the main thread.