4

I have a program that once started, it will executed a flow (few classes involved) several times - each in a different thread. The flow is the same - just different parameters sent to it each time it is invoked.

Each flow will execute on its own thread.

I want to be able to define a file appender (essentially file log) for each thread - so once a flow starts, it programmatically creates its own log file and writes to it.

Searched for it but couldnt find a simple solution for it Can you help?

Ta

oven
  • 88
  • 1
  • 6

4 Answers4

6

You can do this programmatically. e.g.:

class Task implements Runnable {

    private final String path;
    private final String name;

    public Task(String path, String name) {
        this.path = path;
        this.name = name;
    }

    public void run() {
        // Create file appender
        FileAppender appender = new FileAppender();
        appender.setFile(path);
        appender.setLayout(new PatternLayout("%d [%t] %-5p %c - %m%n"));
        appender.activateOptions();

        // Get logger and add appender
        Logger logger = Logger.getLogger(name);
        logger.setAdditivity(false);
        logger.addAppender(appender);

        // Task
        logger.info("Hello World!");

        // Remove appender
        logger.removeAppender(appender);
    }

}

public static void main(String[] args) {
    new Thread(new Task("logs/A.log", "com.company.A")).start();
    new Thread(new Task("logs/B.log", "com.company.B")).start();
}
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0
  1. Define handlers for each log file in the log4j file, for example, this way:

  2. Now add something like this in the same xml file:

        <logger category="a.b.c.d">
            <level name="INFO"/>
            <handlers>
                <handler name="a.b.c.d_FILE"/>
            </handlers>
    
Madhusoodan
  • 560
  • 1
  • 6
  • 18
  • Wanted to create that progrematically as I dont know the amount of threads upfront - see Paul's answer – oven Jan 26 '15 at 18:30
0

Maybe one of those solutions would fit your requirements

There some others on http://stackoverflow.com ;-)

Community
  • 1
  • 1
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
0

You can implement it by yourself:

RandomAccessFile logfile;

public void initLogger(String logPath) {
    File fl = new File(logPath);
    long fileLength = fl.length();
    logfile = new RandomAccessFile(fl, "rw");
    logfile.seek(fileLength);
}

public void log(String text) throws IOException {
    logfile.writeChars(text);
    logfile.writeChar('\n');
}
ancalled
  • 174
  • 6