Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Power Query

Implementing Custom Audit Logging and Lineage Tracking in Power Query M: Capturing Row Counts, Source Metadata, and Transformation Timestamps Across Multi-Step ETL Pipelines

Power Query doesn't ship with an audit framework — but M is expressive enough to build one from scratch. This expert-level lesson walks you through capturing row counts, source metadata, and transformation timestamps at every step of a multi-stage ETL pipeline, then assembling them into a queryable lineage table that loads directly into your data model.

🔥 Expert25 min readNov 25, 2026Updated Nov 25, 2026
Implementing Custom Audit Logging and Lineage Tracking in Power Query M: Capturing Row Counts, Source Metadata, and Transformation Timestamps Across Multi-Step ETL Pipelines
On this page
  • Introduction
  • Prerequisites
  • Why Power Query Needs a Custom Audit Layer
  • Foundational Pattern: Wrapping Steps in Records
  • Building the Audit Log Architecture
  • Component 1: The Audit Record Helper Function
  • Component 2: An Instrumented ETL Query
  • Making Audit Records Externally Accessible
  • Capturing Source Metadata
  • File Source Metadata
  • Database Source Metadata
  • API and Web Source Metadata
  • Assembling the Master Audit Log
  • Computing Row Drop Analysis
  • Tracking Schema Lineage: Column-Level Metadata
  • Persisting Audit History Across Refreshes
  • Surfacing Lineage in Power BI
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Calling `Table.RowCount` Before the Table Is Ready
  • Mistake 2: Forgetting to Remove `TableData` Before Converting to Rows
  • Mistake 3: Timestamps Being Identical Across All Steps
  • Mistake 4: Audit Queries Breaking When Source Schema Changes
  • Mistake 5: Over-Logging Creates Performance Drag
  • Summary & Next Steps

Implementing Custom Audit Logging and Lineage Tracking in Power Query M: Capturing Row Counts, Source Metadata, and Transformation Timestamps Across Multi-Step ETL Pipelines

Introduction

You've built a sophisticated multi-step ETL pipeline in Power Query. It runs every morning, loads data from four source systems, joins them, cleans nulls, pivots a few dimensions, and delivers a clean fact table to your data model. Then one day, your CFO asks: "Why did total revenue drop by 12% this month?" You pull up your query and stare at it. Something filtered out records somewhere — but where? Was it a source issue, a join that dropped rows, or a type conversion that silently coerced values to null? Without audit logging, you're flying blind.

This is the central problem that audit logging and lineage tracking solve. In traditional ETL tools like SSIS or Azure Data Factory, audit frameworks are first-class citizens: they write row counts, timestamps, and source metadata to log tables automatically. Power Query doesn't offer that natively, but the M formula language is expressive enough that you can build it yourself — and when you do, you gain something most Power Query practitioners never have: a complete, queryable audit trail that travels with every refresh cycle.

By the end of this lesson, you'll know how to instrument a multi-step Power Query ETL pipeline with a custom audit log that captures row counts at each transformation stage, records source metadata (file paths, server names, query timestamps), and assembles a lineage table that tells you exactly what happened during the last refresh. You'll also learn how to surface that audit data inside Power BI or Excel without disrupting your production queries.

What you'll learn:

  • How to capture row counts at intermediate transformation steps using M's Table.RowCount and record-wrapping patterns
  • How to record source metadata (connection strings, file paths, last-modified dates) alongside the data they describe
  • How to generate and propagate transformation timestamps through a multi-step pipeline
  • How to assemble a structured audit log table from across multiple independent queries
  • How to design an audit architecture that survives query reordering, pipeline changes, and schema evolution

Prerequisites

This lesson assumes you are comfortable writing M code directly in the Advanced Editor. You should understand how let...in expressions work, how to create and access records, and how functions are defined in M. If you need a refresher, review Understanding the M Formula Language: Syntax, Data Types, and Expression Basics before continuing.

You should also understand how query dependencies work in Power Query, since audit logging relies heavily on the sequencing of evaluations. The article Understanding Query Dependencies and Evaluation Order in Power Query: How the M Engine Executes Your Steps is excellent background.

Familiarity with parameterized queries and function patterns is a plus, since we'll be building reusable logging functions. See Building Reusable Power Query Function Libraries: Parameters, Recursion, and Modular M Code Patterns for the foundational patterns we'll extend here.


Why Power Query Needs a Custom Audit Layer

Before writing a single line of M, it's worth understanding why the native Power Query experience leaves such a gap — and why filling that gap requires deliberate architectural work rather than a checkbox in the UI.

Power Query is a lazy evaluation engine. When you apply a step, M doesn't necessarily execute that step immediately or in isolation. It composes steps into a plan and evaluates the final expression, often folding many steps back to a source system as a single query. This architecture is excellent for performance, but it creates a fundamental tension with audit logging: audit events are side effects, and pure functional languages like M don't have side effects.

What this means in practice: you cannot insert a Log.Write(rowCount) call mid-pipeline the way you would in Python or SQL Server. There's no persistent storage that M writes to during execution. Everything M does is functional — it evaluates expressions and returns values.

The solution is to treat the audit log itself as a value — specifically, a table — that you construct alongside your data transformations. Instead of logging as a side effect, you return the audit information as structured data that another query can read and persist.

Key insight

In M, there are no side effects. This means your audit log cannot be "written" incrementally — it must be computed as a value from metadata you embed deliberately at each step. The mental model shift is from "log events as they happen" to "compute a summary of what happened."

This constraint is actually a feature in disguise. Because your audit log is a table, you can load it into your data model, build DAX measures on top of it, track trends across refreshes (with a little help from incremental patterns), and query it in the same environment where you consume your data.


Foundational Pattern: Wrapping Steps in Records

The core technique for mid-pipeline audit capture in M is the record-wrapper pattern. Instead of a step returning a plain table, it returns a record containing both the table and metadata about that table. Downstream steps can then unpack the data and the metadata separately.

Here's a simple example. Suppose you're loading sales orders from a CSV file:

let
    // Step 1: Load source data
    Source = Csv.Document(
        File.Contents("C:\Data\SalesOrders_2024.csv"),
        [Delimiter=",", Columns=12, Encoding=65001, QuoteStyle=QuoteStyle.None]
    ),
    PromoteHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
    
    // Step 2: Wrap the loaded table with metadata
    SourceAudit = [
        TableData   = PromoteHeaders,
        RowCount    = Table.RowCount(PromoteHeaders),
        StepName    = "Source Load",
        SourcePath  = "C:\Data\SalesOrders_2024.csv",
        LoadedAt    = DateTime.LocalNow()
    ],

    // Step 3: Type the columns
    TypedTable = Table.TransformColumnTypes(
        SourceAudit[TableData],
        {{"OrderID", Int64.Type}, {"OrderDate", type date}, {"Amount", Currency.Type}}
    ),

    // Step 4: Wrap again after typing
    TypeAudit = [
        TableData = TypedTable,
        RowCount  = Table.RowCount(TypedTable),
        StepName  = "Type Assignment",
        SourcePath = "C:\Data\SalesOrders_2024.csv",
        LoadedAt  = DateTime.LocalNow()
    ],

    // Final: Return the data for downstream use
    Result = TypeAudit[TableData]
in
    Result

This is functional — but notice we're throwing away the SourceAudit and TypeAudit records. The lineage metadata is computed but never surfaced. The key to building a real audit log is making those intermediate records accessible to a separate query that assembles them into a table.


Building the Audit Log Architecture

The architecture we'll use across this lesson has three components:

  1. Instrumented data queries — Your regular ETL queries, modified to emit audit records as named steps.
  2. An audit assembly query — A separate query that references the named audit steps from each instrumented query and combines them into a single log table.
  3. An audit output table — Loaded into the data model (or to a worksheet) so it can be queried, visualized, or persisted.

Let's build each component properly.

Component 1: The Audit Record Helper Function

Rather than hand-writing record literals everywhere, create a reusable function query called fnCreateAuditRecord:

// Query name: fnCreateAuditRecord
(
    stepName    as text,
    sourceName  as text,
    sourceType  as text,
    tableData   as table,
    optional notes as nullable text
) as record =>
let
    AuditRecord = [
        StepName      = stepName,
        SourceName    = sourceName,
        SourceType    = sourceType,
        RowCount      = Table.RowCount(tableData),
        ColumnCount   = List.Count(Table.ColumnNames(tableData)),
        CapturedAt    = DateTime.LocalNow(),
        Notes         = if notes = null then "" else notes,
        TableData     = tableData
    ]
in
    AuditRecord

This function accepts a table and returns a record containing both the table and its metadata. The TableData field means downstream steps can unpack the data, while your audit assembly query can read all the other fields.

Tip

The DateTime.LocalNow() call is re-evaluated each time M computes the expression that contains it. Because of lazy evaluation, the timestamp you see in your audit log represents when that particular step was computed during the final evaluation pass — not necessarily in wall-clock sequence. For most audit purposes, this is fine. If you need strict causality, use DateTime.FixedLocalNow() instead (available in some environments), or accept that all timestamps in a single refresh will be clustered close together.

Component 2: An Instrumented ETL Query

Here's a realistic multi-step pipeline — loading sales orders, joining to a customer dimension, filtering outliers, and aggregating — with audit hooks at each stage:

// Query name: SalesOrders_Processed
let
    // ── STAGE 1: Load raw source ──────────────────────────────────────
    RawSource = Csv.Document(
        File.Contents("C:\Data\Exports\SalesOrders_2024.csv"),
        [Delimiter=",", Columns=12, Encoding=65001]
    ),
    RawWithHeaders = Table.PromoteHeaders(RawSource, [PromoteAllScalars=true]),
    
    Audit_01_RawLoad = fnCreateAuditRecord(
        "01_RawLoad",
        "SalesOrders_2024.csv",
        "CSV File",
        RawWithHeaders,
        "Initial CSV load before any transformations"
    ),

    // ── STAGE 2: Type assignment ──────────────────────────────────────
    TypedData = Table.TransformColumnTypes(
        Audit_01_RawLoad[TableData],
        {
            {"OrderID",    Int64.Type},
            {"CustomerID", Int64.Type},
            {"OrderDate",  type date},
            {"Amount",     Currency.Type},
            {"Region",     type text},
            {"ProductSKU", type text}
        }
    ),
    
    Audit_02_Typed = fnCreateAuditRecord(
        "02_TypeAssignment",
        "SalesOrders_2024.csv",
        "CSV File",
        TypedData,
        "Column types applied; errors may appear if source has unexpected values"
    ),

    // ── STAGE 3: Remove errors ────────────────────────────────────────
    CleanData = Table.RemoveRowsWithErrors(
        Audit_02_Typed[TableData],
        {"OrderID", "OrderDate", "Amount"}
    ),
    
    Audit_03_ErrorsRemoved = fnCreateAuditRecord(
        "03_ErrorsRemoved",
        "SalesOrders_2024.csv",
        "CSV File",
        CleanData,
        "Rows with parse errors on key columns removed"
    ),

    // ── STAGE 4: Filter out test/void orders ─────────────────────────
    FilteredData = Table.SelectRows(
        Audit_03_ErrorsRemoved[TableData],
        each [Amount] > 0 and [OrderID] <> null
    ),
    
    Audit_04_Filtered = fnCreateAuditRecord(
        "04_FilteredPositiveAmounts",
        "SalesOrders_2024.csv",
        "CSV File",
        FilteredData,
        "Zero-amount and null OrderID rows excluded"
    ),

    // ── STAGE 5: Join to Customer dimension ──────────────────────────
    CustomerDim = Customer_Dimension,  // Reference to another query
    
    EnrichedData = Table.NestedJoin(
        Audit_04_Filtered[TableData],
        {"CustomerID"},
        CustomerDim,
        {"CustomerID"},
        "CustomerDetails",
        JoinKind.Left
    ),
    ExpandedData = Table.ExpandTableColumn(
        EnrichedData,
        "CustomerDetails",
        {"CustomerName", "Region", "Segment"},
        {"CustomerName", "CustomerRegion", "CustomerSegment"}
    ),
    
    Audit_05_Enriched = fnCreateAuditRecord(
        "05_CustomerEnrichment",
        "CustomerDimension + SalesOrders",
        "Multi-Source Join",
        ExpandedData,
        "Left join to Customer dimension; unmatched CustomerIDs retain nulls"
    ),

    // ── FINAL: Return the processed data ─────────────────────────────
    Result = Audit_05_Enriched[TableData]

in
    Result

Notice the naming convention: Audit_01_RawLoad, Audit_02_Typed, etc. These named steps are still part of the query's let expression, which means they're accessible by name from other queries that reference SalesOrders_Processed. This is the bridge to our audit assembly query.

Warning

Referencing intermediate steps from another query requires that those steps be named within the let block of the source query. Power Query exposes the final in result when another query references it by query name — it does not expose individual step names. To make audit steps externally accessible, you need a separate "audit export" mechanism, which we cover in the next section.


Making Audit Records Externally Accessible

The warning above is crucial: when Query_B references Query_A, it only gets Query_A's in result. The Audit_01_RawLoad step inside Query_A is invisible to Query_B.

The solution is to create a parallel audit export query for each instrumented data query. This query re-uses the same M logic but returns the audit records instead of the data:

// Query name: SalesOrders_AuditRecords
// This query runs the SAME logic as SalesOrders_Processed
// but returns the audit records instead of the final table.
// Mark this query as "Do not load" in production.
let
    // ── Duplicate the instrumented logic ─────────────────────────────
    RawSource = Csv.Document(
        File.Contents("C:\Data\Exports\SalesOrders_2024.csv"),
        [Delimiter=",", Columns=12, Encoding=65001]
    ),
    RawWithHeaders = Table.PromoteHeaders(RawSource, [PromoteAllScalars=true]),
    Audit_01 = fnCreateAuditRecord("01_RawLoad", "SalesOrders_2024.csv", "CSV File", RawWithHeaders, null),

    TypedData = Table.TransformColumnTypes(Audit_01[TableData],
        {{"OrderID", Int64.Type}, {"CustomerID", Int64.Type},
         {"OrderDate", type date}, {"Amount", Currency.Type},
         {"Region", type text}, {"ProductSKU", type text}}),
    Audit_02 = fnCreateAuditRecord("02_TypeAssignment", "SalesOrders_2024.csv", "CSV File", TypedData, null),

    CleanData = Table.RemoveRowsWithErrors(Audit_02[TableData], {"OrderID", "OrderDate", "Amount"}),
    Audit_03 = fnCreateAuditRecord("03_ErrorsRemoved", "SalesOrders_2024.csv", "CSV File", CleanData, null),

    FilteredData = Table.SelectRows(Audit_03[TableData], each [Amount] > 0 and [OrderID] <> null),
    Audit_04 = fnCreateAuditRecord("04_FilteredPositiveAmounts", "SalesOrders_2024.csv", "CSV File", FilteredData, null),

    // ── Assemble audit records into a table ───────────────────────────
    AuditList = {Audit_01, Audit_02, Audit_03, Audit_04},

    AuditTable = Table.FromRecords(
        List.Transform(
            AuditList,
            each Record.RemoveFields(_, {"TableData"})
        )
    ),

    // ── Add pipeline identifier ───────────────────────────────────────
    WithPipeline = Table.AddColumn(AuditTable, "PipelineName", each "SalesOrders", type text)

in
    WithPipeline

The key step is List.Transform(..., each Record.RemoveFields(_, {"TableData"})) — this strips the actual table data from each audit record before converting to rows, so your audit log doesn't contain nested tables (which would cause problems when loading).

Note

Yes, this means the source data is loaded twice — once by the data query and once by the audit query. This is an unavoidable consequence of M's functional model. For large sources, consider buffering (Table.Buffer) the raw load in a shared helper query that both the data and audit queries reference. This can allow the M engine to cache the result across both queries. See Power Query Performance: Master Folding, Buffering & Optimization Techniques for the details of when buffering actually helps.


Capturing Source Metadata

Row counts are useful, but the richest audit information comes from source metadata — file paths, server names, last-modified timestamps, schema versions, and connection parameters. M provides APIs to capture most of this.

File Source Metadata

When loading from files, you can capture the full path and last-modified date using File.Contents and Folder.Files:

// Get file metadata before loading
FileMetadata = 
    let
        FolderPath = "C:\Data\Exports\",
        FileName   = "SalesOrders_2024.csv",
        FullPath   = FolderPath & FileName,
        
        // Folder.Files returns a table with Name, Date modified, etc.
        FolderContents = Folder.Files(FolderPath),
        FileRow = Table.SelectRows(FolderContents, each [Name] = FileName),
        
        ModifiedDate = if Table.RowCount(FileRow) > 0
                       then FileRow{0}[#"Date modified"]
                       else null
    in
        [
            FilePath      = FullPath,
            FileName      = FileName,
            LastModified  = ModifiedDate,
            MetaCapturedAt = DateTime.LocalNow()
        ]

This record can be passed into your fnCreateAuditRecord or stored separately. The Folder.Files approach is especially powerful when you're combining files from a folder and need to track which file contributed which rows.

Database Source Metadata

When connecting to SQL Server or other relational sources, you can capture the server name, database, and table as part of the audit record:

// Query name: Orders_SQL_AuditRecord
let
    ServerName   = "prod-sql-01.corp.local",
    DatabaseName = "OperationsDB",
    TableName    = "dbo.SalesOrders",
    
    Source = Sql.Database(ServerName, DatabaseName),
    OrdersTable = Source{[Schema="dbo", Item="SalesOrders"]}[Data],
    
    // Filter to current year only
    FilteredOrders = Table.SelectRows(
        OrdersTable,
        each Date.Year([OrderDate]) = Date.Year(DateTime.Date(DateTime.LocalNow()))
    ),

    AuditRecord = [
        StepName       = "01_SQLSourceLoad",
        SourceName     = ServerName & "." & DatabaseName & "." & TableName,
        SourceType     = "SQL Server",
        RowCount       = Table.RowCount(FilteredOrders),
        ColumnCount    = List.Count(Table.ColumnNames(FilteredOrders)),
        CapturedAt     = DateTime.LocalNow(),
        Notes          = "Filtered to current calendar year"
    ]
in
    AuditRecord

Warning

Calling Table.RowCount on an unfiltered SQL table may force a full table scan if the query doesn't fold properly. Always ensure your row-count capture happens after your filter steps, or use Table.Buffer before calling Table.RowCount. See Connecting to SQL Server in Power Query: Native Queries and Credential Management for guidance on ensuring filter steps fold to the source.

API and Web Source Metadata

For HTTP-based sources, you can capture response headers alongside the data:

let
    ApiUrl = "https://api.example.com/v2/orders?date=2024-01-15",
    
    RawResponse = Web.Contents(
        ApiUrl,
        [Headers = [Authorization = "Bearer " & ApiToken]]
    ),
    
    // Capture headers for audit
    ResponseHeaders = Value.Metadata(RawResponse),
    
    ParsedData = Json.Document(RawResponse),
    DataTable  = Table.FromRecords(ParsedData[orders]),
    
    AuditRecord = [
        StepName    = "01_APILoad",
        SourceName  = ApiUrl,
        SourceType  = "REST API",
        RowCount    = Table.RowCount(DataTable),
        ColumnCount = List.Count(Table.ColumnNames(DataTable)),
        CapturedAt  = DateTime.LocalNow(),
        Notes       = "Response captured; header metadata available via Value.Metadata"
    ]
in
    AuditRecord

The Value.Metadata function is an underused gem. For binary values returned by Web.Contents, it can expose response headers including Content-Length, Last-Modified, and custom API headers like rate-limit counters — all of which belong in your audit log.


Assembling the Master Audit Log

Once each pipeline has its own _AuditRecords query, you need a central assembly query that unions them into a single audit log table. This is your master lineage view.

// Query name: AuditLog_Master
let
    // Reference all pipeline audit queries
    SalesOrders_Audit   = SalesOrders_AuditRecords,
    CustomerDim_Audit   = CustomerDim_AuditRecords,
    ProductDim_Audit    = ProductDim_AuditRecords,
    InventoryFact_Audit = InventoryFact_AuditRecords,

    // Combine all audit tables
    AllAuditTables = {
        SalesOrders_Audit,
        CustomerDim_Audit,
        ProductDim_Audit,
        InventoryFact_Audit
    },

    CombinedAudit = Table.Combine(AllAuditTables),

    // Ensure consistent column types
    TypedAudit = Table.TransformColumnTypes(
        CombinedAudit,
        {
            {"StepName",    type text},
            {"SourceName",  type text},
            {"SourceType",  type text},
            {"RowCount",    Int64.Type},
            {"ColumnCount", Int64.Type},
            {"CapturedAt",  type datetime},
            {"PipelineName",type text},
            {"Notes",       type text}
        }
    ),

    // Add a refresh batch ID for grouping all steps within one refresh
    // We use the minimum CapturedAt as a proxy for refresh start
    RefreshBatchStart = List.Min(Table.Column(TypedAudit, "CapturedAt")),
    
    WithBatchID = Table.AddColumn(
        TypedAudit,
        "RefreshBatchID",
        each Text.From(Date.Year(DateTime.Date(RefreshBatchStart))) 
           & Text.PadStart(Text.From(Date.Month(DateTime.Date(RefreshBatchStart))), 2, "0")
           & Text.PadStart(Text.From(Date.Day(DateTime.Date(RefreshBatchStart))), 2, "0")
           & "_"
           & Text.PadStart(Text.From(Time.Hour(DateTime.Time(RefreshBatchStart))), 2, "0")
           & Text.PadStart(Text.From(Time.Minute(DateTime.Time(RefreshBatchStart))), 2, "0"),
        type text
    ),

    // Sort for readability
    SortedAudit = Table.Sort(
        WithBatchID,
        {{"PipelineName", Order.Ascending}, {"StepName", Order.Ascending}}
    )

in
    SortedAudit

This query produces a table like:

PipelineName StepName SourceName SourceType RowCount ColumnCount CapturedAt RefreshBatchID Notes
SalesOrders 01_RawLoad SalesOrders_2024.csv CSV File 48,221 12 2024-01-15 06:03:12 20240115_0603 Initial CSV load
SalesOrders 02_TypeAssignment SalesOrders_2024.csv CSV File 48,221 12 2024-01-15 06:03:14 20240115_0603 Types applied
SalesOrders 03_ErrorsRemoved SalesOrders_2024.csv CSV File 48,197 12 2024-01-15 06:03:14 20240115_0603 24 rows removed
SalesOrders 04_FilteredPositiveAmounts SalesOrders_2024.csv CSV File 47,853 12 2024-01-15 06:03:15 20240115_0603 344 rows excluded

Now you can see, in one glance, that 24 rows were lost to type errors and 344 more were filtered as zero-amount orders. If total revenue dropped, you have a starting point.


Computing Row Drop Analysis

The audit log table is useful on its own, but you can derive even more value by computing row drop percentages — the fraction of rows lost at each step compared to the source load. This is a lineage calculation you can do directly in M:

// Query name: AuditLog_WithDropAnalysis
let
    Base = AuditLog_Master,

    // For each pipeline, find the initial row count (Step 01)
    InitialCounts = Table.Group(
        Table.SelectRows(Base, each Text.StartsWith([StepName], "01_")),
        {"PipelineName"},
        {{"InitialRowCount", each List.Max([RowCount]), Int64.Type}}
    ),

    // Join initial counts back to full audit log
    WithInitial = Table.NestedJoin(
        Base,
        {"PipelineName"},
        InitialCounts,
        {"PipelineName"},
        "InitialData",
        JoinKind.Left
    ),
    Expanded = Table.ExpandTableColumn(
        WithInitial, "InitialData", {"InitialRowCount"}, {"InitialRowCount"}
    ),

    // Compute absolute and relative row drop vs. initial load
    WithDropCount = Table.AddColumn(
        Expanded,
        "RowsDropped",
        each [InitialRowCount] - [RowCount],
        Int64.Type
    ),
    WithDropPct = Table.AddColumn(
        WithDropCount,
        "DropPct",
        each if [InitialRowCount] = 0 then null
             else Number.Round(([InitialRowCount] - [RowCount]) / [InitialRowCount] * 100, 2),
        type number
    )

in
    WithDropPct

Key insight

The DropPct column is what turns your audit log from a data record into a diagnostic tool. A drop of 0.05% might be expected (error rows, test data). A drop of 15% at a join step is a red flag that your merge key has unexpected nulls or format mismatches. Building a DAX measure in Power BI that alerts when DropPct exceeds a threshold lets you catch these issues the moment a refresh completes.


Tracking Schema Lineage: Column-Level Metadata

Row counts tell you how many rows survived each step. Column-level metadata tells you what shape your data took at each stage. This is especially valuable when working with dynamic schema changes where a source might add, remove, or rename columns between refreshes.

Add column tracking to your fnCreateAuditRecord function:

// Enhanced version of fnCreateAuditRecord with schema capture
(
    stepName    as text,
    sourceName  as text,
    sourceType  as text,
    tableData   as table,
    optional notes as nullable text
) as record =>
let
    ColumnInfo = Table.ColumnNames(tableData),
    ColumnTypes = Table.Schema(tableData),
    
    // Serialize column names as a pipe-delimited string for easy storage
    ColumnList = Text.Combine(ColumnInfo, " | "),
    
    // Detect nullable columns (useful for data quality tracking)
    NullableColumns = Table.SelectRows(
        ColumnTypes,
        each [AllowNull] = true
    ),
    NullableCount = Table.RowCount(NullableColumns),

    AuditRecord = [
        StepName         = stepName,
        SourceName       = sourceName,
        SourceType       = sourceType,
        RowCount         = Table.RowCount(tableData),
        ColumnCount      = List.Count(ColumnInfo),
        ColumnNames      = ColumnList,
        NullableColCount = NullableCount,
        CapturedAt       = DateTime.LocalNow(),
        Notes            = if notes = null then "" else notes,
        TableData        = tableData
    ]
in
    AuditRecord

The ColumnNames field stored as a pipe-delimited string gives you a snapshot of the schema at each step. If a column disappears between the raw load step and the enrichment step, your audit log will show a different column list — and you'll know exactly where the schema changed.

Tip

Table.Schema returns a detailed table including column names, types, and nullability, but it can be expensive on wide tables. If performance is a concern, substitute Table.ColumnNames (which is very cheap) and skip Table.Schema for high-frequency refresh pipelines.


Persisting Audit History Across Refreshes

One limitation of this architecture is that every refresh produces a new audit log — it doesn't accumulate history. To build a true historical audit trail, you need a persistence mechanism.

For Power BI Premium or Fabric environments, you can write the audit log to a Lakehouse table or Dataflow Gen2 sink. For Excel or Power BI Desktop scenarios, the most practical option is to write audit records to a persistent Excel table or SharePoint list that serves as your audit sink, then have a separate Power Query load that appends new records to that sink.

The pattern connects cleanly to incremental refresh and persistent state techniques. Here's the high-level approach:

// Query name: AuditLog_Persist
// This query reads the existing audit history and appends current refresh records

let
    // Load existing audit history from persistent sink
    ExistingHistory = Excel.CurrentWorkbook(){[Name="AuditHistory"]}[Content],
    
    // Get current refresh audit log
    CurrentAudit = AuditLog_Master,
    
    // Combine and deduplicate by RefreshBatchID + StepName
    Combined = Table.Combine({ExistingHistory, CurrentAudit}),
    
    Deduped = Table.Distinct(Combined, {"RefreshBatchID", "PipelineName", "StepName"}),
    
    // Keep only the last 90 days of history
    Cutoff = DateTime.From(Date.AddDays(DateTime.Date(DateTime.LocalNow()), -90)),
    Recent = Table.SelectRows(Deduped, each [CapturedAt] >= Cutoff)
    
in
    Recent

The result of this query is loaded back to the AuditHistory named table in Excel, overwriting the previous contents. On each refresh, the new audit records are merged in and old records beyond the retention window are pruned.


Surfacing Lineage in Power BI

Once AuditLog_Master is loaded into your Power BI data model, you can build a lineage dashboard. Here are the most useful views:

Pipeline health card: A card visual showing the minimum DropPct across all final steps — anything above a threshold (say, 1%) turns red. This is your at-a-glance pipeline health indicator.

Row count waterfall: A waterfall chart showing row counts by StepName within a selected PipelineName. Each bar represents the cumulative row loss at that step. This is the visual equivalent of your audit log — you can literally see where rows disappear.

Schema change timeline: Using the ColumnNames field, a table visual sorted by CapturedAt lets you see when column lists changed. Pair this with conditional formatting to highlight rows where ColumnCount differs from the previous step in the same pipeline.

Source freshness matrix: Using SourceName and CapturedAt, a matrix showing each source and when it was last loaded. This catches stale sources — if your customer dimension loaded at 2am but your orders loaded at 6am, the join used yesterday's customer data.


Hands-On Exercise

Apply everything from this lesson to build a complete audit-logged pipeline for a realistic scenario. Use this as your exercise brief:

Scenario: You're building an ETL pipeline for a retail analytics team. You have three sources:

  • StoreTransactions.csv — 50,000+ rows of point-of-sale transactions
  • A SQL Server table dbo.Products with product metadata
  • A SharePoint list StoreLocations with store attributes

Your task:

  1. Create the fnCreateAuditRecord helper function as defined in this lesson.

  2. Build an instrumented query Transactions_Processed that:

    • Loads StoreTransactions.csv
    • Types the columns (TransactionID as Int64, Date as date, Amount as Currency, ProductID as Int64)
    • Removes error rows
    • Filters to transactions where Amount > 0
    • Joins to dbo.Products (left join on ProductID)
    • Places an fnCreateAuditRecord call after each step
  3. Build a parallel Transactions_AuditRecords query that runs the same logic and returns the assembled audit table (without TableData).

  4. Build an AuditLog_Master query that combines Transactions_AuditRecords with at least one other pipeline's audit records.

  5. Extend the audit table with the RowsDropped and DropPct columns from the drop analysis section.

Verification: Your audit table should have at least 5 rows (one per step), and the row counts should decrease monotonically from the raw load to the final output. If they don't — investigate why.

Stretch goal: Add a ColumnNames column to each audit record and write a step in your assembly query that flags any step where ColumnCount differs from the previous step in the same pipeline.


Common Mistakes & Troubleshooting

Mistake 1: Calling `Table.RowCount` Before the Table Is Ready

If you call Table.RowCount on an unfiltered reference to a SQL table that hasn't been fully evaluated yet, M may issue a separate database query just to count rows. This can double your query time on large sources.

Fix: Only call Table.RowCount after Table.Buffer on the final filtered result of a step, or accept that the count will trigger an additional evaluation. For non-SQL sources where this isn't a folding concern, the overhead is usually acceptable.

Mistake 2: Forgetting to Remove `TableData` Before Converting to Rows

If you call Table.FromRecords on your audit record list without first removing the TableData field, each row will contain a nested table value. Power Query will display this as [Table] in the cell, and when you try to load the query, it will likely throw a type error.

Fix: Always use List.Transform(AuditList, each Record.RemoveFields(_, {"TableData"})) before Table.FromRecords.

Mistake 3: Timestamps Being Identical Across All Steps

Because M uses lazy evaluation, all DateTime.LocalNow() calls within a single query may resolve to virtually the same instant. If you're using timestamps to understand how long each step takes, they won't give you useful data within a single query.

Fix: Accept that timestamps in M are refresh-time markers, not step-duration timers. For step timing, use Power BI's performance analyzer or Profiler tools in SQL Server if the source is relational.

Mistake 4: Audit Queries Breaking When Source Schema Changes

If you've hardcoded column names in your Table.TransformColumnTypes step and the source adds a new column, your audit query may throw an error on the new column.

Fix: Combine your audit framework with schema-resilient patterns from Handling Dynamic Schema Changes in Power Query. Specifically, only type columns you know will be present and use try...otherwise wrappers around type steps.

Mistake 5: Over-Logging Creates Performance Drag

It's tempting to put an fnCreateAuditRecord call after every single step — 10, 15, 20 checkpoints per query. But each call invokes Table.RowCount, Table.ColumnNames, and DateTime.LocalNow(), and the audit queries re-run the pipeline logic entirely. For large datasets, this can add significant refresh time.

Fix: Be strategic. Capture audit records at meaningful boundaries: after raw load, after type assignment, after major filtering, and after joins. Five checkpoints per pipeline is usually sufficient to diagnose problems without materially impacting performance.

Warning

If your audit query and your data query both reference the same Csv.Document() or Sql.Database() call without buffering, the M engine may evaluate the source twice per refresh. For expensive or rate-limited sources — like paid APIs — this matters a lot. Consider extracting the raw source load into a dedicated "staging" query (marked as "Do Not Load") that both the data and audit queries reference. This aligns with the architecture described in Building Multi-Stage Staging Architectures in Power Query.


Summary & Next Steps

You've now built a complete audit logging and lineage tracking system in pure M code. Here's what the architecture gives you:

  • Row-level accountability — you know how many rows entered and exited every transformation stage.
  • Source metadata capture — file paths, server names, modified dates, and API endpoints are recorded alongside the data they produced.
  • Transformation timestamps — every audit record is stamped to the refresh batch, giving you a time-ordered history of pipeline execution.
  • Schema lineage — column counts and names at each step expose when upstream schema changes affect your pipeline.
  • A queryable, loadable audit table — all of this is surfaced as a standard Power Query table that loads into your data model alongside your fact and dimension tables.

The most important design principle to carry forward: in M, logging is a value, not a side effect. You don't write to a log file — you compute a log table. That shift in thinking is what makes this entire approach possible, and it's what makes Power Query's audit logs actually usable in the same analytical environment where you consume your data.

Where to go next:

  • If your pipelines span multiple query refresh dependencies, Orchestrating Multi-Query Refresh Dependencies in Power Query will show you how to ensure audit queries don't create circular dependencies or evaluate out of order.
  • To extend your audit log with error-handling logic that captures why rows failed — not just that they did — dive into Debugging and Error Handling in M: Building Robust try-otherwise Logic.
  • If you're building this for a team and want the audit function to live in a shared, version-controlled function library, the patterns in Building Reusable Power Query Function Libraries show you how to manage that at scale.
  • For tracking not just row counts but which specific rows changed between refreshes — a natural extension of lineage tracking — explore Automating Incremental Data Refreshes in Power Query with Persistent State and Change Tracking.

The pipeline that woke you up at 3am wondering where 12% of revenue went? After this lesson, it won't surprise you again.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Power Query Essentials

Previous

Connecting to and Querying SharePoint Excel Files in Power Query: Accessing, Filtering, and Refreshing Workbooks Stored in SharePoint and OneDrive

Related Insights

Power QueryPractitioner

Implementing Custom Query Parameterization via Function Currying in Power Query M: Building Composable, Argument-Driven Transformation Pipelines for Multi-Context Reuse

21 min
Power QueryPractitioner

Connecting to and Querying SharePoint Excel Files in Power Query: Accessing, Filtering, and Refreshing Workbooks Stored in SharePoint and OneDrive

21 min
Power QueryFoundation

Understanding Value Types and Primitive Operations in M: Numbers, Text, Logical, and Null Foundations

16 min

On this page

  • Introduction
  • Prerequisites
  • Why Power Query Needs a Custom Audit Layer
  • Foundational Pattern: Wrapping Steps in Records
  • Building the Audit Log Architecture
  • Component 1: The Audit Record Helper Function
  • Component 2: An Instrumented ETL Query
  • Making Audit Records Externally Accessible
  • Capturing Source Metadata
  • File Source Metadata
  • Database Source Metadata
  • API and Web Source Metadata
  • Assembling the Master Audit Log
  • Computing Row Drop Analysis
  • Tracking Schema Lineage: Column-Level Metadata
  • Persisting Audit History Across Refreshes
  • Surfacing Lineage in Power BI
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Calling `Table.RowCount` Before the Table Is Ready
  • Mistake 2: Forgetting to Remove `TableData` Before Converting to Rows
  • Mistake 3: Timestamps Being Identical Across All Steps
  • Mistake 4: Audit Queries Breaking When Source Schema Changes
  • Mistake 5: Over-Logging Creates Performance Drag
  • Summary & Next Steps