2

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
Peter Brockmann
  • 3,594
  • 3
  • 28
  • 28
Khushi
  • 103
  • 9
  • 1
    [Related question](https://stackoverflow.com/questions/36170962/how-to-append-hostname-to-log-file-in-log4j-xml). Did you check all the associated answers to see if they already answer your question? – Giacomo Alzetta Jul 10 '19 at 12:57

1 Answers1

0
  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) {

        }
    }
}
Rachit07
  • 44
  • 5
  • Where we are using Environment environment? – Khushi Jul 11 '19 at 07:14
  • 1
    @Khushi I didn't get you. FYI Environment is a interface in Spring and it holds property of system & application i.e which profile,port & management port the what is the configuration of vm and so on. We can conclude as it holds metric info. – Rachit07 Jul 17 '19 at 08:23