Logging is an important means of being able to determine what is going on in any system. This is particularly true for otherwise opaque systems in the cloud.
API Gateway offers the ability to log through Cloudwatch by providing the handler with a Context object containing a logging service in its getLogger property. We can obtain this in our handler, wrap it in a "generic" interface (to log a string) and then pass that to any userspace handlers that want it.
These changes are tagged AWS_GATEWAY_LOGGING in the repository.
So, in TDAHandler we add this constructor:
ServerLogger logger = new AWSLambdaLogger(cx.getLogger());
The AWSLambdaLogger is define as:public class AWSLambdaLogger implements ServerLogger {
private final LambdaLogger logger;
public AWSLambdaLogger(LambdaLogger logger) {
this.logger = logger;
}
@Override
public void log(String string) {
logger.log(string);
}
}
Finally, in ProcessorRequest we pass it off to anybody who asks for it by implementing the DesiresLogger interface: if (handler instanceof DesiresLogger) {
((DesiresLogger)handler).provideLogger(logger);
}
It would, of course, be possible to integrate this with frameworks such as SLF4J by providing a suitable implementation of the concrete classes. This is left as an exercise to the reader (but look at aws-lambda-java-log4j).If you don't have access to "the context" you can still log. You just need to obtain the logger from a static method on LambdaRuntime:
LambdaLogger logger = LambdaRuntime.getLogger();
One thing to note (if you are unused to Cloudwatch Logging): it often takes a while for logging to work its way through Amazon's cloud. This can be very distracting, particularly since a lot of issues never seem to get logged at all. How do you determine if a log failed to get through, or just hasn't come through yet? And having to wait a minute or two (sometimes more) for feedback on what just went wrong can kill productivity. Sadly, I don't have a solution for this other than to "test" as little as possible on AWS and to always assume that every time you push everything except the environment is perfect. And then to change the environment as little as possible, and always in small steps so that it is always "green" to "green" and any time you do see a failure, you know what the problem "must be".Next: Getting Started with Websockets
No comments:
Post a Comment