5

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

4 Answers 4

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

You nailed it. Appreciate it paul
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>
    

1 Comment

Wanted to create that progrematically as I dont know the amount of threads upfront - see Paul's answer
0

Maybe one of those solutions would fit your requirements

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

Comments

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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.