Search code examples
javaspring-bootapplication.properties

How can i get port number on which my application is running in logging format?


How can I get host-name or post number under logging information? This didn't work:

logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} %d{localhost}  ---- %msg%n

Solution

    1. You need to implement ApplicationListener<EmbeddedServletContainerInitializedEvent> with your spring boot main class.
    2. Embedded servlet container will provide you exact port number in which your application is initialize.
    3. Host Address/Name can be fetched using innet address.
    4. Replace System.out.println to logger.info()

    For your reference :

    @SpringBootApplication
    @EnableSwagger2
    public class SpringBootAppMain implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
        @Autowired
        Environment environment;
        public static void main(String[] args) {
            SpringApplication.run(SpringBootAppMain.class, args);
        }
    
        @Override
        public void onApplicationEvent(EmbeddedServletContainerInitializedEvent embeddedServletContainerInitializedEvent) {
            System.out.println("Port " + embeddedServletContainerInitializedEvent.getApplicationContext().getEmbeddedServletContainer().getPort());
            try {
                System.out.println("HOST Address " + InetAddress.getLocalHost().getHostAddress());
                System.out.println("Host Name " + InetAddress.getLocalHost().getHostName());
            } catch (UnknownHostException e) {
    
            }
        }
    }