OTLP logs without the SDK: four traps that still return 200

You already have a collector. Your vendor already speaks OTLP. All you want is to send your log lines there, and the official path is the OpenTelemetry SDK plus a handful of peer packages and an initialisation order you have to get right.
So you skip it. OTLP over HTTP with a JSON body is a published wire format — you can POST to /v1/logs yourself in about eighty lines. I did exactly that for my logger, and the first version worked. The collector answered 200. The logs showed up.
Then I started checking the numbers, and found four separate ways an OTLP payload can be wrong while every single request still returns 200.
That is the part nobody warns you about. A 200 from an OTLP endpoint does not mean “your data is correct.” It means “I parsed your JSON.” Those are very different promises.
flowchart TD
A[Your POST to /v1/logs] --> B{Valid JSON?}
B -->|No| C[400 — you find out immediately]
B -->|Yes| D{Field names known?}
D -->|No| E[Ignored silently<br/>spec says receivers MUST ignore unknown fields]
D -->|Yes| F{Types loosely compatible?}
F -->|Yes| G[200 OK]
G --> H[Precision lost<br/>timestamps flattened<br/>severity misfiled<br/>trace link broken]
style G fill:#2d6a4f,color:#fff
style H fill:#9b2226,color:#fffHere is each trap, what I measured, and the line of code that fixes it.
Trap 1: a bare number for intValue is accepted, and quietly rounded
Every guide tells you the same thing: in OTLP JSON, 64-bit integers are strings. {"intValue": "4200"}, never {"intValue": 4200}.
I believed the usual reason for that rule — that a collector rejects the bare number. I was wrong. I loaded the real logs.proto from the OpenTelemetry proto repo and pushed both shapes through it:
intValue as STRING "4200" -> ACCEPTED
intValue as NUMBER 4200 -> ACCEPTEDBoth fine. No error, no warning. The protobuf JSON mapping says so directly for int64: the value “will be a decimal string,” and then, one sentence later, “Either numbers or strings are accepted.”
So why bother with the string? Because of what happens above 2^53, where a JavaScript number stops being able to hold every integer:
sent as string -> decoded: 9007199254740993 | wanted: 9007199254740993
sent as number -> decoded: 9007199254740992 | wanted: 9007199254740993Off by one. No exception anywhere. That number could be a Twitter-style snowflake ID, a nanosecond reading from process.hrtime.bigint(), a database bigint primary key — any of the values you would actually want in a log line when you are trying to find one specific event.
The fix is one String():
case 'number':
return Number.isInteger(value)
? { intValue: String(value) } // not `value`
: { doubleValue: value }
case 'bigint':
return { intValue: String(value) }The rule is right. The reason everybody gives for it is not. You are not avoiding a rejection — you are avoiding a rounding that nothing reports.
This is the same failure mode I hit from the other direction in one BigInt in your log data deletes every other field: JavaScript’s number type and 64-bit integers do not fit together, and the seam between them is where log data goes missing.
Trap 2: ms * 1e6 — the bug is not where you think
OTLP wants nanoseconds. Date.parse() gives you milliseconds. The obvious move is to multiply by a million.
Everyone who has written about this says the multiplication is lossy because the result blows past Number.MAX_SAFE_INTEGER. That first half is true — a 2026 timestamp in nanoseconds is about 1.79e18, roughly 200 times the safe limit.
So I checked how often it actually produces the wrong string. I ran 200,000 timestamps through both paths and compared each against an exact BigInt computation:
samples: 200000
float bits inexact: 150000 (75.0%)
String() output wrong: 0 (0.0%)Three quarters of those floats are genuinely wrong at the bit level. 1790164800123 * 1e6 is not 1790164800123000000 in memory — it is 1790164800123000064, 64 ns off.
And String() prints it correctly anyway. Every time. JavaScript renders the shortest decimal that round-trips back to the same float, and for a value in this range that is the number you meant. JSON.stringify uses the same algorithm, so the digits that reach the collector are right.
I had expected to find corrupted timestamps on the wire. There are none.
The damage shows up the moment you do arithmetic. Two timestamps 250 ms apart:
duration via float ns : 249999872 ns (want 250000000)
exact via BigInt : 250000000128 ns short, on a window you measured to the millisecond. Harmless on its own. Now try the thing people reach for when two log lines land in the same millisecond and a backend sorts them randomly — nudge each one forward by a nanosecond:
record 0: 1790164800000000000
record 1: 1790164800000000000
record 2: 1790164800000000000
record 3: 1790164800000000000
record 4: 1790164800000000000Five records, five increments, one timestamp. At that magnitude the gap between neighbouring floats is 256, so + 1 lands on the number you started from. The de-duplication does nothing and reports no failure. With BigInt the same loop gives you ...000, ...001, ...002, ...003, ...004.
Skip the arithmetic entirely and the whole class of problem disappears:
function toUnixNano(isoTimestamp: string): string {
const ms = Date.parse(isoTimestamp)
const safeMs = Number.isFinite(ms) ? ms : Date.now()
return `${safeMs}000000` // six zeros, no multiplication
}Those six digits are honestly zero. You measured milliseconds; you are stating the same value in the unit the protocol asks for. If you ever need real sub-millisecond precision, reach for BigInt — never a float.
Trap 3: severity — the spec tells you which number to pick
OTel severity is a 1–24 scale carved into named bands: 1–4 TRACE, 5–8 DEBUG, 9–12 INFO, 13–16 WARN, 17–20 ERROR, 21–24 FATAL.
Five bands, four slots each. Which slot do you use for a logger whose levels are just debug, info, warn, error, fatal?
I had written a comment in my own source claiming the middle of each band was safer, on a vague theory about filters behaving oddly at band edges. There is no such behaviour, and the spec answers the question outright:
If the source format has only a single severity that matches the meaning of the range then it is recommended to assign that severity the smallest value of the range.
The logs data model then gives the reason in its display table. The smallest value in each band is the one whose short name is the plain level: 5 is DEBUG, 9 is INFO, 13 is WARN, 17 is ERROR, 21 is FATAL. Six is DEBUG2. Ten is INFO2. Pick the middle and your info lines show up in a dashboard labelled INFO3.
const SEVERITY_NUMBER: Record<LogLevel, number> = {
debug: 5, // DEBUG (6, 7, 8 are DEBUG2/3/4)
info: 9, // INFO
warn: 13, // WARN
error: 17, // ERROR
fatal: 21, // FATAL
}One more thing the spec is strict about, and this one does break: OTLP JSON requires enum fields as integers. "severityNumber": 17 is correct; "severityNumber": "SEVERITY_NUMBER_ERROR" is forbidden, even though ordinary protobuf JSON allows the name form. A permissive parser will take it and your payload stops being portable between collectors.
Trap 4: traceId is hex here, not base64
This is the one that quietly costs you the feature you went to OTLP for.
In the protobuf schema, trace_id is a bytes field. The standard protobuf JSON mapping encodes bytes as base64. OTLP explicitly does not:
The
traceIdandspanIdbyte arrays are represented as case-insensitive hex-encoded strings; they are not base64-encoded as is defined in the standard Protobuf JSON Mapping.
That deviation is not cosmetic. I fed a normal 32-character hex trace ID to a generic protobuf JSON decoder — one that follows the base64 rule — and watched it produce 24 bytes where OTLP wants 16. Garbage, accepted without complaint, because base64 and hex share an alphabet well enough to decode into something.
A W3C traceparent header already carries hex. An OTel span’s spanContext().traceId is already hex. So you get this right by doing nothing — as long as you never “helpfully” base64-encode it on the way out.
The placement matters just as much. traceId and spanId are first-class fields on the LogRecord, beside body and severityNumber. They are not entries in the attributes array:
return {
timeUnixNano,
observedTimeUnixNano: timeUnixNano,
severityNumber: SEVERITY_NUMBER[entry.level],
severityText: SEVERITY_TEXT[entry.level],
body: { stringValue: entry.message },
attributes,
...(entry.context.traceId ? { traceId: entry.context.traceId } : {}),
...(entry.context.spanId ? { spanId: entry.context.spanId } : {}),
}Put the trace ID in an attribute instead and the payload is still valid, still returns 200, still appears in your log search. It just never nests inside the span in a trace waterfall, because the backend reads the dedicated field to build that link. You end up with logs and traces in the same system and no connection between them — which is the entire thing you were trying to buy. Where the trace ID comes from in the first place is a separate problem, and I covered it in correlating logs across a request with AsyncLocalStorage and OpenTelemetry.
Two smaller ones worth thirty seconds
The path. OTLP defines /v1/logs. Vendor dashboards hand you the base URL sometimes and the full path other times. Append it if it is missing, leave it alone if it is there, and a copy-pasted config works either way:
const url = options.url.endsWith('/v1/logs')
? options.url
: `${options.url.replace(/\/$/, '')}/v1/logs`Get this wrong and you get a 404 that reads exactly like an outage.
service.name. Most backends key their whole UI on it. Without one your logs still arrive and are effectively unfindable, mixed in with everything else hitting that collector. Default it to something wrong-but-present — a wrong name is easy to spot and override, a missing one shows up as “why can’t I find anything.”
What a correct OTLP payload looks like
I ran the finished exporter against a plain http.createServer on a random port and printed what it posted. Two records, one with nested data:
{
"resourceLogs": [{
"resource": { "attributes": [
{ "key": "service.name", "value": { "stringValue": "checkout-api" } }
]},
"scopeLogs": [{
"scope": { "name": "@developerehsan/nextjs-logger" },
"logRecords": [{
"timeUnixNano": "1790164800123000000",
"observedTimeUnixNano": "1790164800123000000",
"severityNumber": 17,
"severityText": "ERROR",
"body": { "stringValue": "charge failed" },
"attributes": [
{ "key": "amount", "value": { "intValue": "4200" } },
{ "key": "ratio", "value": { "doubleValue": 0.5 } }
],
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"spanId": "00f067aa0ba902b7"
}]
}]
}]
}The request landed on /v1/logs even though I configured the bare host. 4200 went out as a string, 0.5 as a number. Severity 17 with the text ERROR. Trace and span IDs as hex, at the top level.
One detail in there I did not plan for: data is caller-supplied and can nest as deep as anyone wants, so the encoder recurses. A depth cap turns that into a bounded cost, falling back to a JSON string past four levels. Without it, one pathological object logged in a hot path can exhaust the stack — and the crash happens inside your logger, which is the last place you want to be debugging.
Check it yourself in five minutes
You do not need a collector to catch three of these four. Point the exporter at a local server and read the body:
import http from 'node:http'
const server = http.createServer((req, res) => {
let body = ''
req.on('data', (c) => (body += c))
req.on('end', () => {
console.log(req.url, JSON.stringify(JSON.parse(body), null, 2))
res.writeHead(200).end('{}')
})
})
server.listen(0)Then read four lines of the output. Is intValue quoted? Does timeUnixNano end in six zeros and sit inside quotes? Is severityNumber a bare integer at a band base? Are traceId and spanId hex, at the top of the record rather than inside attributes?
Four questions, and a failure on any of them looks identical to success from the outside.
The takeaway
Adopting a wire protocol does not require adopting the SDK that implements it. It does require reading the spec more carefully than the error responses force you to, because OTLP’s receivers are deliberately forgiving: unknown fields are ignored by design, and loose types are accepted by the protobuf JSON mapping underneath.
Every one of these four defects returned 200. Two of them I only found by testing a claim I had already written down as fact — including one in my own source comments that turned out to be backwards. If you hand-roll this, verify the payload rather than the status code. The status code was never going to tell you.