Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j ThreadContext MultiThread won't inherit

Tags:

java

log4j

I encounter this post's problem
Here my sample of code

public class StackOverflow implements RequestHandler<Map<String, String>, ApiGatewayResponse> {
    private static final Logger LOGGER = LogManager.getLogger(StackOverflow.class);

    public abstract class StreamGobbler extends Thread {
        // Working Interceptor using this.print("message")
        public abstract void print(String line);
    }

    private class ErrStreamGobbler extends StreamGobbler {
        ErrStreamGobbler(InputStream in) { super(in); }

        @Override
        public void print(String line) { LOGGER.error(line); }
    }

    private class OutStreamGobbler extends StreamGobbler {
        OutStreamGobbler(InputStream in) { super(in); }

        @Override
        public void print(String line) { LOGGER.info(line); }
    }


    // MAIN METHOD
    @Override
    public ApiGatewayResponse handleRequest(Map<String, String> params, Context context) {
        // ThreadContext propagation
        System.setProperty("isThreadContextMapInheritable", "true");
        ThreadContext.put("foo", "bar");

        LOGGER.info("Hello from main");

        // My process will return value on System.in & System.out
        ProcessBuilder pb = new ProcessBuilder("sh", String.format("batchs/JOB_FOO/run.sh"));
        Process p = pb.start();
        // Intercept those logs
        new ErrStreamGobbler(p.getErrorStream()).start();
        new OutStreamGobbler(p.getInputStream()).start();
        p.waitFor();
    }
}

The ThreadContext from LOGGER.info("Hello from main"); does work and also prints foo: bar.
But my child threads StreamGobbler doesn't get ThreadContext and won't print foo: bar as a log4j property event if isThreadContextMapInheritable is set to true.

like image 530
IQbrod Avatar asked Oct 28 '25 03:10

IQbrod


1 Answers

Just encountered this problem. Found setting -DisThreadContextMapInheritable=true at application startup works, even though setting it in the code does not.

like image 92
jonathan Avatar answered Oct 29 '25 18:10

jonathan