如何利用Log4j在日志中输出16进制的线程ID-CSDN论坛

2024-11-26 05:50:14
推荐回答(1个)
回答1:

一个例子:
1。java class
package com.netcobol.log;

import org.apache.log4j.*;

/**
*

Title:


*

Description:


*

Copyright: Copyright (c) 2003


*

Company:

棚判慧
* @author not attributable
* @version 1.0
*/

import org.apache.log4j.*;
import com.sinotrans.util.PropertyUtil;

// How to use log4j
public class TestLogging {

// Initialize a logging category. Here, we get THE ROOT CATEGORY
//static Category cat = Category.getRoot();
// Or, get a custom category
static Category cat = Category.getInstance(TestLogging.class.getName());
static {
try{
org.apache.log4j.PropertyConfigurator.configure(PropertyUtil.getProperty(
"log4j.properties"));
}catch(Exception e){

}
}
// From here on, log away! Methods are: cat.debug(your_message_string),
//冲蠢 cat.info(...), cat.warn(...), cat.error(...), cat.fatal(...)

public static void main(String args[]) {
// Try a few logging methods
cat.debug("Start of main()");
cat.info("Just testing a log message with priority set to INFO");
cat.warn("Just testing a log message with priority set to WARN");
cat.error("链答Just testing a log message with priority set to ERROR");
cat.fatal("Just testing a log message with priority set to FATAL");
try {
org.apache.log4j.PropertyConfigurator.configure(PropertyUtil.getProperty("xxx.properties"));

}
catch (Exception ex) {
ex.printStackTrace();
cat.error("Failed to load xxx.proerties", ex);
}
// Alternate but INCONVENIENT form
cat.log(Priority.DEBUG, "Calling init()");

new TestLogging().init();
}

public void init() {
java.util.Properties prop = System.getProperties();
java.util.Enumeration enum = prop.propertyNames();

cat.info("***System Environment As Seen By Java***");
cat.debug("***Format: PROPERTY = VALUE***");

while (enum.hasMoreElements()) {
String key = (String) enum.nextElement();
cat.info(key + " = " + System.getProperty(key));
}
}

}

2.
#### Use two appenders, one to log to console, another to log to a file
log4j.rootCategory=debug, stdout, R

# Print only messages of priority WARN or higher for your category
log4j.category.your.category.name=WARN
# Specifically inherit the priority level
#log4j.category.your.category.name=INHERITED

#### First appender writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

#### Second appender writes to a file
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=c:/example.log

# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n