Logging to Amazon’s DynamoDB from Zend Framework 2

I recently had to write an app that would run in Amazon Beanstalk. The thing with Beanstalk is that you can set some server metric to trigger automatic scaling (up or down) for your EC2 instances so you cannot count on any particular instance to be there at any time. So, any logging you do to a local file will be lost when the instance is destroyed. This is why I had to write something that could log to DynamoDB so that my logs would be untouched if the instances ceased to exist.

I found that doing this in ZF2 was incredibly easy. This pretty much took me 10 minutes and the best thing was that it required almost no code change at all other than instanciating my new writer and passing it to my file logger before using it.

Here’s the code:

You might be wondering what the $origin bit is all about. This is not necessary in order to log to DynamoDb but in my case I had to identify each instance somehow so I ended up passing an $origin string which would contain some of that particular EC2 instance’s identification (I think it was the instance ID plus the public DNS or something).