Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

java - How do I setup log4j properties so that each thread outputs to its own log file?

I have multiple instances of a thread class running at any given time. I have log4j setup to be used for logging needs.

I need a way to setup log4j so that every instance of my thread class outputs its log in a different log file.

Here is what I have done ( in pseudo code)

public class doSomething extends Thread {

    private Logger d_logger;

    public doSomething(int id){
       d_logger = Logger.getLogger("doSomething"+id);
       String logFileName = "doSomething"+id+".log";

       Properties prop = new Properties;
       prop.setProperty("doSomething"+id,"DEBUG, WORKLOG");
       prop.setProperty("log4j.appender.WORKLOG","org.apache.log4j.FileAppender");
       prop.setProperty("log4j.appender.WORKLOG.File", logFileName);
       prop.setProperty("log4j.appender.WORKLOG.layout","org.apache.log4j.PatternLayout");
       prop.setProperty("log4j.appender.WORKLOG.layout.ConversionPattern","%d %c{1} - %m%n");
       prop.setProperty("log4j.appender.WORKLOG.Threshold","INFO"); 

       PropertyConfigurator.configure(prop);
    }

    public void run(){
       d_logger.info("Starting to doSomething number" + id);
    }

}

Though the above creates a file for every thread I instantiate, It does not output anything to those files. Any help is much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's not outputting anything to the files because the correct syntax for setting up a logger is:

prop.setProperty("log4j.logger.doSomething"+id,"DEBUG, WORKLOG");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...