Logging and Alerts
🎯 Introduction
The previous articles covered collecting data. This one covers making it visible: log levels organize records for investigation, and alert rules proactively notify people about anomalies instead of relying on someone checking logs after a failure.
By the end of this article, you will be able to:
- Use the debug, info, warn, and error log levels appropriately.
- Build a simple logger with level filtering and sampling.
- Design threshold alerts and historical comparison alerts while avoiding alert fatigue.
🧱 How Logs Differ from Event Tracking
Logs are text records produced by a running program. They describe what the program is doing and its current state, primarily for developers and operations teams. Event tracking, covered in article three, describes user actions, primarily for product and business operations teams. Tracking is like a shopping center's cameras measuring foot traffic and purchases; logs are like equipment records showing whether the machinery is working. Together, they help reconstruct what happened in production.
🧱 Log Levels and When to Use Them
A production application can generate many logs each day. Without severity levels, investigation means reading them one by one. Levels let you start with error records and quickly narrow the search.
From lowest to highest severity: debug → info → warn → error:
- debug: development details such as current variable values. High volume and usually low value in production, where it is typically disabled.
- info: successful milestones such as a user logging in. These records help reconstruct the steps of an operation later.
- warn: something unusual without a failure, such as retrying a timed-out request or using a default for a missing parameter. Worth reviewing.
- error: an actual feature failure, such as a failed API request or submission. These commonly trigger notifications.
🛠 Building a Simple Logger
Scattering console.log calls throughout the code causes two problems: disabling low-level logs later requires editing many files, and the output stays in users' browsers where you cannot retrieve it. A shared logger centralizes level filtering, sampling, and reporting. This implementation runs directly in the browser without third-party packages:
const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }; // Higher numbers mean greater severity
const minLevel = 'info'; // Minimum output level; 'info' disables debug in production
function log(level, message, extra) {
if (LEVELS[level] < LEVELS[minLevel]) {
return; // Discard records below the minimum level
}
const record = { level, message, extra, time: new Date().toISOString() };
console[level](`[${level}]`, message, extra ?? '');
if (LEVELS[level] >= LEVELS.warn) {
report(record); // Also send warn and error records to the server
}
}
function report(record) {
// Use sendBeacon to continue reporting as the page closes
navigator.sendBeacon('/api/logs', JSON.stringify(record));
}
export const logger = {
debug: (msg, extra) => log('debug', msg, extra),
info: (msg, extra) => log('info', msg, extra),
warn: (msg, extra) => log('warn', msg, extra),
error: (msg, extra) => log('error', msg, extra),
};
Use it like console, for example logger.error('Login API request failed', { status: 500 }), but every record includes a level and timestamp. Change minLevel to disable lower levels without editing business logic. Production projects often use Sentry's logging and reporting capabilities; see Integrating Sentry for setup.
💡 Sampling to Control Log Volume
Reporting every high-frequency, low-value log, such as info records for every operation, wastes bandwidth and obscures important information. Keep a sample instead:
// Sample reporting: send only 10% of records
function reportWithSample(record, rate = 0.1) {
if (Math.random() < rate) {
report(record);
}
}
The rule is: report all warn and error records; sample only high-frequency info and debug records.
🧱 Designing Alert Rules
Alerts continuously check metrics against rules and notify you about anomalies. Two common approaches are:
Threshold alerts: notify when a fixed limit is exceeded.
Use these for metrics with a clear limit, such as more than 50 error records in one minute:
// Alert when there are more than 50 errors in the last minute
function checkErrorCount(errorCountInLastMinute) {
if (errorCountInLastMinute > 50) {
sendAlert(`${errorCountInLastMinute} errors in one minute. Investigate promptly.`);
}
}
The difficulty is choosing the limit: daytime and overnight traffic differ, so a single threshold may create daytime false positives or miss overnight incidents.
Historical comparison alerts: compare against past values rather than a fixed limit.
- Previous-period comparison: compare this hour with the preceding hour, for example.
- Same-period comparison: compare a matching time slot, such as 10 a.m. today with 10 a.m. yesterday.
For example, alert when this hour's error count exceeds three times yesterday's count for the same hour. Daytime and overnight each get an appropriate baseline, reducing false positives from normal traffic variation while detecting sudden anomalies:
// Compare with the same period yesterday; alert when the count exceeds three times the baseline
function checkBySamePeriod(todayCount, yesterdayCount) {
const hasBaseline = yesterdayCount > 0;
const ratio = hasBaseline ? todayCount / yesterdayCount : 0;
if (hasBaseline && ratio > 3) {
sendAlert(`Error count is ${Math.round(ratio)} times the same period's baseline. Investigate promptly.`);
}
}
🧰 Where to Send Alerts
Common channels include email, WeCom group bots, and Feishu group bots. If you use Sentry, configure an Alert Rule in its dashboard instead of writing this code yourself. For a group bot, the platform provides a webhook URL; sending it a POST request posts a message in the group:
function sendAlert(text) {
fetch('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your-key', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ msgtype: 'text', text: { content: text } }),
});
}
🪤 Avoiding Alert Fatigue
If an alert channel receives hundreds of mostly unactionable messages a day, people soon mute it and miss important notifications. This is alert fatigue. A few ways to address it:
- Make every alert actionable: recipients need a clear action to take. Otherwise, include the information in an ordinary report.
- Group similar alerts: if one endpoint fails 100 times in a minute, send one summary.
- Add a cooldown: suppress repeat notifications for the same problem for a period such as 10 minutes.
- Match channels to severity: post warn notifications in a group; reserve calls or text messages for error notifications.
❓ Questions and Answers
Q1: How do I distinguish warn from error?
Ask whether the feature failed. Use error when an operation fails or the user cannot complete an action. Use warn when it still works but shows unusual behavior such as retries, fallbacks, or default values.
Q2: Could sampling miss critical problems?
Sample only frequent, low-value logs, and always report every error and warn record. Sampling reduces count precision rather than eliminating all evidence: keeping 100 out of 1,000 similar info records still shows the flow operating normally.
Q3: What is a suitable alert threshold?
There is no standard answer. Start by observing: use permissive thresholds and record triggers without notifying anyone. After collecting a week or two of data, set the threshold near the upper edge of normal variation, then refine it based on false positives and missed incidents.
🧪 Exercises
Exercise 1: Add sampling to this logger: report 20% of info records and all error records:
function report(level, record) {
// Write your code here: sample info at 20% and report every error
navigator.sendBeacon('/api/logs', JSON.stringify(record));
}
Exercise 2: Complete this previous-period comparison function to alert when the current error count exceeds twice the previous period's count. Handle a previous count of zero:
function checkByLastPeriod(currentCount, lastCount) {
// Write your code here: call sendAlert when the count exceeds twice the previous period's count
}
🎉 You now know how to work with logs and alerts! This completes the frontend monitoring course. Revisit the Frontend Monitoring course, then put these techniques into practice in one of your projects.
