Eurig Jones
Eurig Jones

Reputation: 8543

App Engine Instance ID

Is it possible to get info on what instance you're running on? I want to output just a simple identifier for which instance the code is currently running on for logging purposes.

Upvotes: 4

Views: 2712

Answers (4)

broc.seib
broc.seib

Reputation: 22731

Not sure about before, but today in 2021 the system environment variable GAE_INSTANCE appears to contain the instance id:

instanceId = System.getenv("GAE_INSTANCE")

Upvotes: 0

Scott
Scott

Reputation: 428

Even better, you should wrap the call in a try catch so that it will work correctly locally too.

Import this

import com.google.appengine.api.modules.ModulesException;
import com.google.appengine.api.modules.ModulesServiceFactory;

Then your method can run this

String instanceId = "unknown";
try{
    instanceId = ModulesServiceFactory.getModulesService().getCurrentInstanceId();
} catch (ModulesException e){
    instanceId = e.getMessage();
}

Without the try catch, you will get some nasty errors when running locally.

I have found this super useful for debugging when using endpoints mixed with pub-sub and other bits to try to determine why some things work differently and to determine if it is related to new instances.

Upvotes: 1

Su Zhang
Su Zhang

Reputation: 2270

With the advent of Modules, you can get the current instance id in a more elegant way:

ModulesServiceFactory.getModulesService().getCurrentInstanceId()

Upvotes: 1

Ibrahim Arief
Ibrahim Arief

Reputation: 9106

Since there is no language tag, and seeing your profile history, I assume you are using GAE/J?

In that case, the instance ID information is embedded in one of the environment attributes that you could get via ApiProxy.getCurrentEnvironment() method. You could then extract the instance id from the resulting map using key BackendService.INSTANCE_ID_ENV_ATTRIBUTE.

Even though the key is stored in BackendService, this approach will also work for frontend instances. So in summary, the following code would fetch the instance ID for you:

String tInstanceId = ApiProxy.getCurrentEnvironment()
                             .getAttributes()
                             .get( BackendService.INSTANCE_ID_ENV_ATTRIBUTE )
                             .toString();

Please keep in mind that this approach is quite undocumented by Google, and might subject to change without warning in the future. But since your use case is only for logging, I think it would be sufficient for now.

Upvotes: 3

Related Questions