0

I have requirement to append port number to log file. Is ther any property or variable available to get running server port? I tried local.server.port property, but this will get initalize only after spring context is initialized completely.

If port number is not possible, is there any tomcat instance level information is avaiable to get in application properties?

All application properties are stored in config server.

Ashwin Patil
  • 1,307
  • 1
  • 23
  • 27
  • when do you want to get the property,before the spring context is initialized? – neo Aug 12 '19 at 06:49
  • please check below https://stackoverflow.com/questions/3867197/get-the-server-port-number-from-tomcat-without-a-request – GPopat Aug 12 '19 at 06:59
  • Does'nt the startup logs have the port information ? You can create another log appender for tomcat to print it into another log. Also if you want to do it through code - it means code managed via Spring so that would happen only after/during Spring is being initialized. Or you can write code in a ServletContext listener. Can you elaborate on why you want to do that exactly? – Shailendra Aug 12 '19 at 06:59
  • Please refer to below https://stackoverflow.com/questions/3867197/get-the-server-port-number-from-tomcat-without-a-request – GPopat Aug 12 '19 at 07:02
  • Yes, Before context is initialized. Once bean post processors are executed, spring makes call to config server and read properties. at this point i need running server port information – Ashwin Patil Aug 12 '19 at 07:04
  • What port number? Tomcat can listen on any number of ports. Typicaly at least two, one for HTTP and one for HTTPS. What you should be doing is using the port number of the current request, which is only available during the current request. – user207421 Aug 12 '19 at 09:56
  • You could [set tomcat port number with a -D property](https://stackoverflow.com/a/15556920/2834978) and use that property on logback config. – LMC Aug 12 '19 at 16:22

2 Answers2

0

You can add the following in logback xml to load the spring configuration properties

 <property resource="application.properties"/> 

then spring properties can be fetched using simple spring EL expression, example:

 <fileNamePattern>%d{yyyy-MM-dd}-${server.port}.log</fileNamePattern>

will create the file as 2019-08-12-8080.log where 8080 is the port number. Hope it helps.

Mohit Singh
  • 496
  • 2
  • 11
  • Thank you your answer, but this picks the value defined in the properties file. Say in the properties file i defined server.port=8080, i might run this application on tomcat server, which is running on port say 8090. when i retrive server.port, it gives me 8080 but it should be 8090. – Ashwin Patil Aug 12 '19 at 13:07
0

You can read the port from the context and define as a spring property.

<springProperty scope="context" name="server_port" source="server.port"/>