Log Analytics Query Interface

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Lesson: Mastering the Log Analytics Query Interface in Microsoft Sentinel

Introduction: Why Querying Matters in Security Operations

In the modern security landscape, the ability to collect data is only half the battle. You can ingest petabytes of logs from firewalls, cloud infrastructure, identity providers, and endpoints, but that data remains inert and useless unless you can effectively interrogate it. Microsoft Sentinel, as a cloud-native Security Information and Event Management (SIEM) solution, relies on Kusto Query Language (KQL) to bridge the gap between raw, unstructured log data and actionable security intelligence.

The Log Analytics query interface is the primary workspace where security analysts, threat hunters, and incident responders spend the majority of their time. It is not merely a search bar; it is a powerful analytical engine that allows you to slice, dice, aggregate, and visualize data in real-time. Understanding how to navigate this interface and write efficient, precise queries is a foundational skill for anyone responsible for defending an organization’s digital assets. Without mastery of this interface, you are effectively blinded, unable to distinguish between routine administrative noise and the subtle signals of a persistent adversary.

This lesson will guide you through the mechanics of the Log Analytics interface, the structure of KQL, and the best practices required to turn logs into answers. We will move beyond basic syntax and explore how to build complex queries that support threat hunting, incident investigation, and the creation of custom detection rules.


Not read yet

Understanding the Log Analytics Environment

The Log Analytics interface is built upon the Azure Data Explorer platform. When you open the "Logs" blade within your Microsoft Sentinel workspace, you are presented with a multi-pane environment designed to facilitate rapid exploration.

The Anatomy of the Workspace

  1. The Tables Pane: Located on the far left, this lists all the data tables ingested into your workspace. Understanding your schema—what tables exist and what columns they contain—is the first step to any investigation.
  2. The Query Editor: This is the main text area where you write your KQL. It includes features like IntelliSense, which suggests table names, operators, and column names as you type.
  3. The Time Picker: Located in the top toolbar, this allows you to scope your search. Always be mindful of your time range; querying "last 30 minutes" versus "last 30 days" will drastically change your results and the cost of the query execution.
  4. The Results Pane: This is where the output of your query is displayed. You can sort, filter, and export these results. It also provides the ability to render charts and graphs directly from the query output.

Callout: The Power of Schema Awareness Many beginners struggle because they do not understand the schema of the logs they are querying. Before you write a single line of code, spend time in the Tables pane. Familiarize yourself with the Common Information Model (CIM) or the Azure Monitor schema. Knowing whether a source IP is stored in IPAddress, SrcIP, or ClientIP saves hours of frustration.


Not read yet

The Fundamentals of Kusto Query Language (KQL)

KQL is a read-only query language. It is designed to be highly efficient for large-scale data processing. The language follows a pipe-delimited structure, where the output of one command is passed as the input to the next. This creates a logical flow that is easy to read and debug.

Basic Syntax and Structure

A typical KQL query starts with the table name, followed by a series of operators. Here is a simple example:

// This is a comment in KQL
SecurityEvent
| where TimeGenerated > ago(24h)
| where EventID == 4624
| summarize Count = count() by Account
| sort by Count desc

In this example:

  • SecurityEvent identifies the source table.
  • | (the pipe operator) passes the data to the next step.
  • where filters the data to specific criteria (time and event ID).
  • summarize aggregates the data to count occurrences per user.
  • sort by organizes the results for better readability.

Essential Operators for Security Analysis

To become proficient, you must master the core operators used daily in security operations centers (SOCs):

  • where: Filters rows based on specific boolean conditions. Use this to reduce your dataset as early as possible in the query to improve performance.
  • project: Selects specific columns. Use this to clean up the output and focus on the data that matters for your current investigation.
  • extend: Creates a new calculated column. This is incredibly useful for parsing strings or performing arithmetic on log data.
  • summarize: Performs aggregations (count, sum, avg, min, max). This is the key to identifying patterns and statistical anomalies.
  • join: Combines data from two different tables based on a common key. This is essential for correlating, for example, sign-in logs with identity protection alerts.
  • render: Visualizes the data as a chart (e.g., render timechart or render barchart).

Note: KQL is case-sensitive for column names and values unless you use specific case-insensitive operators (like =~ instead of ==). Always check your casing if a query returns zero results when you expect data.


Not read yet

Step-by-Step: Investigating a Potential Security Incident

Let’s walk through a real-world scenario: Investigating a potential "Brute Force" attack on an internal server.

Step 1: Identifying the Scope

First, we need to identify failed sign-in attempts on a specific server. We will look at the SecurityEvent table.

SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4625 // 4625 is the Windows Event ID for a failed login
| where Computer == "SRV-PROD-01"

Step 2: Aggregating the Data

Now, we want to see which accounts are being targeted and how many failed attempts are occurring over time.

SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4625
| where Computer == "SRV-PROD-01"
| summarize FailedAttempts = count() by Account, bin(TimeGenerated, 1h)
| sort by FailedAttempts desc

Step 3: Visualizing the Trend

To see if there is a spike, we can render this as a time chart.

SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4625
| where Computer == "SRV-PROD-01"
| summarize FailedAttempts = count() by bin(TimeGenerated, 1h)
| render timechart

By following these steps, we move from raw logs to a clear visualization of a potential attack, allowing for a much faster decision-making process.


Not read yet

Advanced Querying Techniques

Once you are comfortable with basic filtering and aggregation, you can start leveraging advanced techniques to perform deeper analysis.

Using join to Correlate Data

Correlation is the bread and butter of security monitoring. Often, you need to link an alert in the SecurityAlert table to the specific sign-in activity in the SigninLogs table.

let AlertData = SecurityAlert
| where TimeGenerated > ago(24h)
| where AlertName contains "Suspicious";
let SigninData = SigninLogs
| where TimeGenerated > ago(24h);
AlertData
| join kind=inner (SigninData) on $left.ExtendedProperties == $right.UserId

Parsing Unstructured Data with extend and extract

Sometimes, logs contain information buried inside a single "Message" or "RawData" field. You can use the extract function or parse operator to pull this data out into its own column.

// Example of extracting an IP address from a raw message string
CommonSecurityLog
| extend SourceIP = extract(@"src=([\d\.]+)", 1, Message)
| where isnotempty(SourceIP)
| summarize count() by SourceIP

Callout: The Importance of Performance In a large environment, inefficient queries can be slow and expensive. Always filter by time first, then by indexed columns (like Computer or Account). Avoid using wildcards (*) at the beginning of strings (e.g., where User contains "*admin"), as these force the engine to scan every single row, which is significantly slower than prefix-based searches.


Not read yet

Best Practices for KQL Development in Sentinel

Writing effective queries is as much about discipline as it is about syntax. Follow these industry-standard practices to ensure your queries are robust and maintainable.

1. Comment Your Code

Always add comments to your queries, especially if they are going to be used in detection rules. Explain the "why" behind the logic, not just the "what." This is invaluable for other analysts who might inherit your work.

2. Use let Statements

The let statement allows you to define variables or create temporary tables. This makes complex queries much easier to read and maintain.

let TimeRange = 24h;
let Threshold = 10;
SecurityEvent
| where TimeGenerated > ago(TimeRange)
| summarize Count = count() by IPAddress
| where Count > Threshold

3. Minimize Data Transfer

Only select the columns you actually need. Using project to limit the output reduces the amount of data the interface needs to render and speeds up query execution.

4. Leverage KQL Functions

If you find yourself writing the same logic repeatedly, create a KQL function. You can save these within the Log Analytics workspace and reuse them across multiple alerts and workbooks.

5. Test with Small Datasets

Before running a query against a full 30-day index, test it with a shorter time window (e.g., 1 hour). Once you verify the logic is correct, you can expand the time range.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced analysts fall into common traps. Recognizing these will save you significant time.

  • The "Time Range" Trap: Forgetting that the time picker in the interface overrides the ago() function in your query. Ensure they are aligned, or better yet, rely on the time picker for consistency.
  • Schema Confusion: Assuming all logs have the same field names. Always verify the schema of the specific table you are using.
  • Case Sensitivity: Using == when you need a case-insensitive match. Use == for exact matches and =~ for case-insensitive matches.
  • Over-reliance on extend: Trying to perform heavy calculations using extend on millions of rows. If possible, filter the data down first, then perform the calculations.
  • Ignoring Data Types: Trying to perform mathematical operations on a string column. Use todouble() or toint() to convert data types before performing math.
Operator Use Case Performance Tip
where Filtering data Place early in the query
project Cleaning output Use only at the end
summarize Aggregating data Use only after filtering
join Correlating tables Ensure the join key is indexed
render Visualizing results Use only for final output

Not read yet

Practical Application: Building a Custom Detection Rule

One of the primary uses of the query interface is to build custom detection rules. Let's create a rule that triggers when a user clears their security event logs—a common indicator of anti-forensic activity.

  1. Open the Logs pane.
  2. Enter the query:
    SecurityEvent
    | where EventID == 1102 // Audit log cleared
    | project TimeGenerated, Computer, Account, EventID, Activity
    
  3. Validate: Ensure the query returns expected results.
  4. Save as Alert Rule: Once satisfied, click the "+ New Alert Rule" button in the toolbar. This will take you to the Sentinel Analytics wizard, where you can map these query results to an incident.

By following this workflow, you ensure that your detection rules are based on tested, verified logic rather than speculative code.


Understanding Data Ingestion and Latency

It is critical to remember that Microsoft Sentinel is a distributed system. There is often a slight delay (latency) between an event occurring on a device and that event appearing in the Log Analytics interface.

  • Ingestion Latency: Data must be collected, sent to the workspace, and processed. This usually takes seconds, but can take longer under heavy load.
  • Query Latency: The time it takes for the engine to scan the tables and return the results.
  • Impact: When building time-sensitive alerts, always add a small buffer. If you are looking for events in the "last 5 minutes," your query might miss events that were ingested 6 minutes ago but occurred 4 minutes ago. It is common practice to look back slightly further than your detection interval to account for this.

Warning: Never assume that the absence of data means the absence of an attack. Always check the health of your data connectors in the Microsoft Sentinel "Data Connectors" blade to ensure logs are actually flowing into the workspace as expected.


Not read yet

Advanced Data Types and Structures

Modern logs often come in JSON format. KQL has powerful functions to handle dynamic data types.

Handling JSON

If a column contains a JSON object, you can access the properties using the . notation.

// Example: Accessing a property inside a dynamic 'Properties' column
SecurityEvent
| extend UserAgent = Properties.UserAgent
| where UserAgent contains "Mozilla"

Using mv-expand

Sometimes, a single log entry contains an array of items (e.g., a list of IP addresses associated with an alert). You can use mv-expand to turn that array into individual rows, making it easier to analyze each item.

// Expanding an array of IPs into individual rows
SecurityAlert
| mv-expand IPAddress = Entities.IPAddresses
| summarize AlertCount = count() by tostring(IPAddress)

Summary of Key Takeaways

  1. Schema is King: Always explore your tables and understand your column names before writing queries. Knowing the structure prevents most errors.
  2. Filter Early: Use the where operator as early as possible to reduce the dataset size. This improves query speed and reduces the cost of processing.
  3. Readability Matters: Use let statements and comments to make your queries professional and easy for your team to understand and audit.
  4. Master the Pipe: Understand that KQL is a linear, pipe-delimited flow. Think of your query as a series of transformations on a data stream.
  5. Test Before Deploying: Never move a query into a production detection rule without testing it against a representative dataset first.
  6. Account for Latency: Always consider that log data may not be perfectly real-time. Build your alerts with enough buffer to account for ingestion delays.
  7. Leverage Visualizations: Use the render operator to turn complex log results into charts. Visual patterns are often much easier to spot than text-based output.

Not read yet

Frequently Asked Questions (FAQ)

Q: Can I use SQL in the Log Analytics interface? A: No, KQL is a distinct language. While it shares some concepts with SQL, the syntax is different. However, most SQL users find KQL quite intuitive after a few hours of practice.

Q: How do I know if my query is efficient? A: When you run a query, the "Results" pane often shows the amount of data processed and the time taken. If your query consistently takes a long time or processes huge amounts of data, look for ways to filter earlier or select fewer columns.

Q: Is there a way to save my queries? A: Yes, the Log Analytics interface has a "Save" button in the top toolbar. You can save your queries to your personal favorites or share them with your team within the workspace.

Q: Why does my query return no results even though I know the data is there? A: This is usually due to one of three things: the time range is set incorrectly, the casing of your filter is mismatched, or you are looking in the wrong table. Double-check your time picker and ensure you are using the correct table schema.

Q: Can I use KQL to modify data? A: No, KQL is strictly a read-only language. You cannot use it to delete or change the raw logs stored in your workspace, which is a key feature for maintaining data integrity in a SIEM environment.

By mastering the Log Analytics query interface, you move from being a passive observer of logs to an active investigator capable of uncovering the most sophisticated threats. Continue to practice by writing queries for different log sources—such as Azure Activity logs, Office 365 logs, and custom application logs—to build your muscle memory and analytical intuition.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.