Skip to content

Commit d99af90

Browse files
authored
Add TraceId and SpanId generator util (open-telemetry#35)
* Add TraceId and SpanId generator util * minor fix * Update file structure
1 parent e712b45 commit d99af90

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Copyright 2019, OpenTelemetry Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import * as crypto from 'crypto';
18+
19+
const SPAN_ID_BYTES = 8;
20+
21+
/**
22+
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
23+
* characters corresponding to 128 bits.
24+
*/
25+
export function randomTraceId(): string {
26+
return randomSpanId() + randomSpanId();
27+
}
28+
29+
/**
30+
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
31+
* characters corresponding to 64 bits.
32+
*/
33+
export function randomSpanId(): string {
34+
return crypto.randomBytes(SPAN_ID_BYTES).toString('hex');
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Copyright 2019, OpenTelemetry Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import * as assert from 'assert';
18+
import { randomSpanId, randomTraceId } from '../src/common/util/id';
19+
20+
describe('randomTraceId', () => {
21+
it('returns different 32-char hex strings', () => {
22+
const traceId = randomTraceId();
23+
assert.ok(traceId.match(/[a-f0-9]{32}/));
24+
});
25+
});
26+
27+
describe('randomSpanId', () => {
28+
it('returns different 16-char hex string', () => {
29+
const spanId = randomSpanId();
30+
assert.ok(spanId.match(/[a-f0-9]{16}/));
31+
});
32+
});

0 commit comments

Comments
 (0)