user1379280
user1379280

Reputation: 347

how to print application name provided in .yml file in every log statement?

I wanna print my application name provided in .yml file in my log4j logs

my log4j pattern is

LOG_PATTERN=[%d{yyyy-MM-dd HH:mm:ss.SSS}] boot%X{context} - ${PID} ${LOG_LEVEL_PATTERN} [%t] --- %c{1}: %m%n

Currently I am getting logs like

2017-09-16 15:53:35.687 INFO 18302 --- [  restartedMain] mc.n.e.EurekaDiscoveryClientConfiguration : My Log print statement

The format i want my logs to print

2017-09-16 15:53:35.687 INFO 18302 --- [**APPLICATION_NAME**] [  restartedMain] mc.n.e.EurekaDiscoveryClientConfiguration : My Log print statement

How can I put the application name in there in log4j log

Upvotes: 1

Views: 1986

Answers (1)

JC Carrillo
JC Carrillo

Reputation: 1026

Assuming this is a web application, you can use a Filter and MDC.

See example:

public class MDCFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        try {
            MDC.put("appName", "**APPLICATION_NAME**");
            chain.doFilter(request, response);
        } finally {
            MDC.remove("appName");
        }
    }
}

The Filter above will put your app name into MDC and then you can use a log pattern to print the app name.

Based on your log pattern, see modification below:

%d{yyyy-MM-dd HH:mm:ss.SSS} boot%X{context} - ${PID} ${LOG_LEVEL_PATTERN} [%t] --- [%X{appName}%n] %c{1}: %m%n

Note: %X{appName}%n which will output what was placed in the filter MDC.put("appName", "**APPLICATION_NAME**");

The above will output the following:

2017-09-16 15:53:35.687 INFO 18302 --- [**APPLICATION_NAME**] [  restartedMain] mc.n.e.EurekaDiscoveryClientConfiguration : My Log print statement

Upvotes: 1

Related Questions