Diagnostics.Trace
ExpressionWrites a trace message if tracing is enabled and returns the provided value.
Syntax
Diagnostics.Trace(traceLevel as number, message as anynonnull, value as any, optional delayed as nullable logical) as anyParameters
| Name | Type | Required | Description |
|---|---|---|---|
traceLevel | number | Yes | The severity level of the trace message. Use TraceLevel.Critical, TraceLevel.Error, TraceLevel.Warning, TraceLevel.Information, or TraceLevel.Verbose. |
message | anynonnull | Yes | The trace message to write. Can be a text value or a zero-argument function that returns text when delayed is true. |
value | any | Yes | The value to return. Can be the actual value or a zero-argument function when delayed is true. |
delayed | logical | No | If true, the evaluation of both message and value is deferred until the trace message is actually consumed, improving performance when tracing is disabled. |
Return Value
any — The value passed as the third argument, returned unchanged after writing the trace message.
Remarks
Diagnostics.Trace writes a trace message to the Power Query diagnostics log (if tracing is enabled) and returns value unchanged. This is the primary function for debugging and instrumenting M queries.
The traceLevel parameter controls the severity of the message using the TraceLevel enumeration:
TraceLevel.Critical— critical failuresTraceLevel.Error— errorsTraceLevel.Warning— warningsTraceLevel.Information— informational messagesTraceLevel.Verbose— detailed diagnostic output
### Delayed evaluation
When delayed is true, both message and value should be zero-argument functions (e.g., () => "my message" and () => expensiveComputation()). This ensures that the message text and value are only computed when the trace is actually being recorded, avoiding unnecessary overhead when tracing is disabled.
### Viewing trace output
To view trace output in Power BI Desktop, enable query diagnostics via Tools > Diagnostics > Start Diagnostics, then run your query and stop diagnostics. The trace messages appear in the diagnostics tables.
Examples
Example 1: Trace a message before a computation
let
Result = Diagnostics.Trace(
TraceLevel.Information,
"Converting number to text",
() => Text.From(123),
true
)
in
#table({"Result"}, {{Result}})Result | |
|---|---|
| 1 | 123 |
Example 2: Trace with a warning level
let
RawValue = null,
Result = if RawValue = null then
Diagnostics.Trace(
TraceLevel.Warning,
"RawValue was null, using default",
0
)
else
RawValue
in
#table({"RawValue", "Result"}, {{RawValue, Result}})RawValue | Result | |
|---|---|---|
| 1 | null | 0 |