Posts

Showing posts from April, 2017

How to chain an ES6 Promise

Node.js uses async functions extensively, as it based around non-blocking I/O. Each function takes a callback function parameter, which can result in some messy, deeply nested callback functions if you have to call a bunch of async functions in sequence. Promises make these callbacks a lot cleaner. ES6 (or ES2016)  Promise s are a great way of chaining together asynchronous functions so that they read like a series of synchronous statements. There's already some great posts on Promises, 2ality has a good intro to async then detail of the api , so I won't rehash that article. However, after starting to use them for cases more complicated than most examples, it easy to make a few mistaken assumptions or make things difficult for yourself. So here is a more complicated example showing a pattern I like to follow. In this example, I'll use the new Javascript Fetch API , which is an API that returns a Promise, allowing you to make async HTTP calls without having to muck a

Adding MDC headers to every Spring MVC request

Mapped Diagnostic Context ( MDC ) logging allows you to set attributes associated with current thread, so that SLF4J (via your logger implementation library) can log those attributes with each logging statement without it having to be specified. For example you could configure logback to log the sessionId on every statement, which is really handy when using a log indexer such as Splunk. This would allow you to easily see all the requests made by a user, for a given session. To use with logback, you'd set the pattern to %-4r [%thread] %-5level sessionId=%X{sessionId} - %msg%n Setting these attributes for each entry point would be a pain so one way would be to implement a ServletRequestListener , which would allow setting the attributes at the start of the request and removing them again at the end of the request. ( Note: It's important to remove the attributes afterwards, as threads are re-used by application servers and will give misleading logging statements) If you&#