Permalink
Browse files

Add a profileSafe method so profiles with same id can be safely inter…

…leved.

When tracking api calls, it's not enough for us to just pass a name as an
id to keep track of the profile call.  This change will return an id
that can be used to close the correct profile call when there are multiple
profile calls with the same id.

I'm not in love with the `profileSafe` name so if you think of something
better I'm good with that.
  • Loading branch information...
1 parent 209e16d commit ffeeed651a91eb85363a15f0752c38110ee30ab4 @lynns committed Mar 27, 2013
Showing with 42 additions and 0 deletions.
  1. +25 −0 index.js
  2. +17 −0 test/metric-log.test.js
View
@@ -17,6 +17,11 @@ module.exports = exports = function metric() {
*/
function noop () {};
+var idGen = Date.now();
+function nextId() {
+ return ++idGen;
+}
+
/**
* Apply a context to the logger
*
@@ -46,6 +51,26 @@ exports.context = function(obj) {
return c._profiles[id] = Date.now();
}
};
+ c.profileSafe = function(id, props) {
+ var prof;
+ if (c._profiles[id]) {
+ prof = c._profiles[id];
+ var time = Date.now() - prof.start,
+ finalProps = merge(prof.props, props || {});
+ delete c._profiles[id];
+ return c(prof.id, time, "ms", finalProps);
+ }
+ else {
+ prof = {
+ start: Date.now(),
+ profId: nextId(),
+ id: id,
+ props: props || {}
+ };
+ c._profiles[prof.profId] = prof;
+ return prof.profId;
+ }
+ };
c.context = function(obj) {
return exports.context(obj).use(c);
};
View
@@ -119,6 +119,23 @@ describe("metric-log", function(){
});
});
+ describe("context.profileSafe(id)", function(){
+ it("should allow interlieved profile calls with same id", function(done) {
+ var call1 = context.profileSafe('my-api-test-call', {callId: 1}),
+ call2 = context.profileSafe('my-api-test-call', {callId: 2});
+ setTimeout(function() {
+ context.profileSafe(call2);
+ str.should.match(/measure=my-api-test-call/);
+ str.should.match(/callId=2/);
+
+ context.profileSafe(call1);
+ str.should.match(/measure=my-api-test-call/);
+ str.should.match(/callId=1/);
+ done();
+ }, 50);
+ });
+ });
+
describe("context.profile(id)", function(){
it("should profile a function call", function(done) {
context.profile('my-api-test-call');

0 comments on commit ffeeed6

Please sign in to comment.