All notes

Worker Logs Should Explain Failures Without Recording Requests

Design stable event schemas, safe correlation and bounded observability failure behavior.

English edition, edited for length. Read the complete Chinese original.

console.log(request) While seemingly convenient, it could potentially output tokens from cookies and query parameters, as well as user input. However, the completeness of logs doesn’t necessarily equate to their usefulness. What’s truly important is knowing which request failed at which step, how many users were affected, and whether the issue can be reliably reproduced.

This article uses the example of a “Worker” calling upstream interfaces. Log retention, sampling, and available fields vary depending on the product and plan, so it’s important to confirm the current capabilities before designing. You should not assume that all edge requests will be fully saved.

Reconstructing the Required Evidence from Obstacle Avoidance Issues

Assume that the new search interface occasionally fails. The maintainer needs to know whether the failure occurred during index loading, upstream calls, or response parsing, and to determine the extent of the impact. The log model can be defined around this path, with start, upstream completion, parsing failure, and final result, without needing to record the search query itself. Each field supports an action: deployment identifier for version comparison, stage for locating boundaries, duration for identifying slow dependencies, and correlation identifier for finding the same request.

When a field cannot be used, do not record it initially. A complete URL includes search terms and tokens, and a user ID can create a long-term profile. The original response may contain private data. Convenience in blocking is not an unlimited justification for data collection. Prioritize using routing templates and error categorization, and establish permissions, retention, and de-identification rules for data that is actually needed. The value of structured logging is the ability to perform stable queries, not simply converting any object into JSON to make it secure.

console.error(JSON.stringify({
  event: 'upstream_request_failed',
  requestId,
  route: '/api/search',
  deployment: version,
  upstreamStatus: response.status,
  durationMs,
}));

Route templates are more suitable for aggregation than full URLs, avoiding each slug or search term becoming a separate dimension. Request IDs are used to link events within a single request, and deployment versions help identify differences before and after releases. Error categorization should be stable, and exceptions should not be treated as a single categorization field.

If accepting request IDs from external sources, it’s important to limit their length and character set to prevent log injection or expensive field usage. If necessary, create a unique ID for this site and store the verified upstream IDs in a separate field. The association identifier should not be used as a substitute for user authentication or authorization checks.

Correlation Identifiers: Passed Through the Call Chain, But Not Trusted

The external request ID may be controlled by an attacker. Initially, restrict the format and length. If necessary, generate a site identifier. The identifier passed to the upstream system is used for diagnostics and should not affect identity or tenant determination. The tracking values returned by the upstream system are only used for data logging and should not be treated as trusted configuration values. Each boundary is stored in a normal, structured field to avoid line breaks or abnormal characters disrupting log lines.

When asynchronous tasks continue to execute after a request returns, the batch or task identifier is still associated with the originating request. Avoid using only an incrementing number within a single instance, as this can lead to duplication and be reset upon redeployment. The identifier’s scope must be clearly defined, whether it’s for a single request, a single task, or cross-service tracking. Log correlation does not require revealing user identities, and the two objectives can be separated.

Dates and durations are also kept separate. Event times are used for sorting and cross-system comparison, while durations are measured using appropriate timing sources. Clock adjustments should not result in negative durations. The order in which logs from different regions arrive may vary, and the order of collection should not be interpreted as a causal relationship. Key steps are preserved, maintaining the parent-child relationship, which reduces the reliance on complete time synchronization.

Distinguishing between Metrics, Logs, and Tracing Work

The metrics are suitable for answering questions about failure rates, latency distributions, and request volumes. Logs are suitable for viewing specific events. Tracing is suitable for understanding cross-service call paths. Writing the entire content of each request to logs and then offline calculation of all metrics is expensive and makes it difficult to quickly identify anomalies.

Sampling can reduce costs, but it requires separate consideration of errors and rare paths. Only sampling successful requests may miss critical failures, and only logging errors may result in a lack of a normal baseline. Explain the sampling strategy before presenting the statistical conclusions, and do not treat a subset of samples as a complete representation of all requests.

Each search term, original path, and user ID serves as an index label, resulting in a large number of sequences and increasing storage and query costs. The index uses a limited routing and state category, while the specific request context remains in a controlled sampling log. Summarization or hashing does not automatically reduce cardinality, and hashing each search term still results in the same number of different values, potentially retaining associated risks. Anonymization and aggregation are distinct actions and should not be used together.

Sampling strategies impact statistical interpretation. Simple random sampling is suitable for estimating common results, but rare errors may be missed. Retaining error-prone samples can help identify the root cause, but it cannot directly calculate the overall failure rate. The “complete count” metric provides the denominator, while the “log sample” provides the reason. Combining both provides a more complete picture. Record the sampling rules and version to avoid misinterpreting changes in the number of logs after modifying the sampling rate as changes in business traffic.

The log budget includes event volume, the number of requests per event, and the retention period. A loop processes each log record, which can generate significant output, especially under legitimate requests. To manage this, define limits. When these limits are exceeded, truncate or aggregate the log data, rather than silently pretending it’s complete. The platform’s logging capabilities are designed with planned differences. Even when storage is limited, core requests should still function normally. Diagnostic logging can be observed during performance degradation.

Sensitive fields require an allowed list

Do not use the approach of “removing a few known secret fields” for any request object. New fields added in the future will still leak information. Instead, use a whitelist approach, and only record the route, status, time, and necessary categories. Search terms, email addresses, IP addresses, and user IDs may all involve privacy, so they should be restricted or anonymized based on their intended use.

The request body is typically not suitable for default logging. While controlled diagnostics can be temporarily enabled to troubleshoot specific issues, they require authorization, scope, a deadline, and deletion rules. The error stack may also contain internal paths and parameters. Error text intended for public responses should be kept separate from internal logs.

The whitelist is not only applied to successful events. Exception objects, third-party SDKs, and stacks may contain request parameters, and a generic error serialization will re-expose fields that have already been avoided in logging. Create separate, secure structures for public responses and internal logs. Unknown objects should only be logged with their category and essential summary. Do not recursively print the entire cause chain without depth and field limits.

The fake token testing is performed in the request header, query, body, upstream error, and nested fields, ensuring that no original values are output from any path. Whether personal data such as email and IP addresses need to be recorded depends on the purpose. Deleting passwords is not equivalent to completing a privacy check. The temporary switch has a defined duration and scope, and automatically closes and enforces retention policies after use. Access to log viewing should also be minimized, and data masking is not a reason to make it available to everyone.

External logging platforms may accept cross-border transfers and long-term retention. The project must confirm its policies. Security event logs and regular performance logs can have different access and retention requirements, but both should have clear owners. When users delete data, the implications for logs should be handled according to legal and business policies. It is not possible to guarantee that all systems will immediately erase logs. Technical measures services have clear policies and do not replace policy judgments.

After going live, you should be able to answer a specific question.

For example, when encountering the question “Why does the new version search interface occasionally return a 502 error?”, we can investigate by:

  • Filtering by deployment version and route query.
  • Distinguishing between upstream status, timeouts, and parsing errors.
  • Using the requestId to identify the complete sequence of events.

If the logs only contain “failed” without any categorization or timing information, we can only rely on guesswork.

Alerts should be based on user impact and stability windows, rather than notifying for every error. A single expected 404 error does not necessarily indicate a system failure, but a sudden increase in 404 errors may indicate a routing migration issue. Pages that consistently return 200 status codes, even when using degraded data, should also have independent metrics that expose the long-term degradation.

If a failure occurs upstream and is successfully retried, it may not affect users, but a sudden increase in the retry count still indicates a risk. An alert should be composed of failure rate, latency, and degradation ratio, with a defined stable window and recovery conditions. Version 404 requires distinguishing between normal crawlers, old links, and new versions, and cannot be notified in a single message. The alert should inform the maintainer to first check which version and which stage is affected, rather than simply stating “an error has occurred.”

The logging system itself should not enter an infinite recursion in case of failure. The limited local diagnostics and whether the core interface continues to serve should be determined by business requirements. Do not call the same failed reporting function again in the error handling of the logs. The queue buffer should also have a capacity and discarding rules to prevent diagnostic traffic from overwhelming normal requests. Observability has its own failure patterns and requires practice.

Log Pattern Upgrade Requires Compatibility with Existing Queries

After renaming fields, it may still be possible to query old fields. However, actual failures may not be reported. The event model can include versioning, and important queries and dashboards should be updated together when the schema changes. During migration, limited compatibility is provided, and duplicate fields are not permanently retained. Event names should express the facts, such as a failed upstream request, rather than vague “debug” or “error” messages. The same fact should remain stable across versions to facilitate comparison.

It’s also important to observe failures in log parsing. In addition to structured output, if there are multiple lines of stack traces, the parser might split them into multiple unrelated events. Use a platform-supported structured format and limit field sizes, and test with unusual text and special characters. Do not manually concatenate JSON; a standard serializer can correctly escape it, but you still need to perform a whitelist check on the object content. Correct formatting and data security are two separate checks.

Instead of relying on individuals to remember specific backend operations, save example queries for core troubleshooting issues. For example, a query like “Distribution of timeout categories for a specific version and route” can directly support incident response. Similarly, the policy of restricting access to only necessary personnel and exporting data is maintained. Even after exporting logs from the platform to local tables, personal data may still be present, and this data cannot be easily removed simply by leaving the platform.

After diagnosis, verify that temporary fields and high sampling are disabled. The debugging switch is often left on during troubleshooting, but then forgotten, leading to ongoing costs and privacy risks. The switch should have an automatic expiration date and a designated owner, with records indicating when it was disabled. The expanded sampling range should have a specific reason and duration, rather than treating the production environment as a permanent experimental setting.

The long-term value of the logs comes from their stable semantics and actionable information. Maintainers should be able to quickly identify which release, which stage, and which requests were affected, without knowing any user passwords or input data. Regularly removing unnecessary fields, fixing categories, and validating queries is more effective than continuously adding more console output, and will improve troubleshooting efficiency.

Reconstructing the Minimal Event Model from a Fault Query

The problem is that “Version B search returns more than 502,” and the required fields are deployment version, route template, upstream result category, stage duration, and association with the request, rather than all user inputs. First, compare the impact ratio of versions A and B using a complete count, and then examine the stage details from a controlled error sample. If the logs only record the final status, it would be impossible to determine whether the failure originated from the connection, the upstream status, or JSON parsing; and if all the content is recorded but without stage information, the question still cannot be answered.

You can define an end-request event, including the final result and total duration, as well as a few key stage events. The successful path typically doesn’t require logging the start and end of each function; rare failures can retain more detailed but anonymized context. There is a budget for the number of events, and when processing 100 results, do not generate 100 complete objects. The set of fields is maintained around the query, and you should not treat JSON serialization as a license to record arbitrary information.

Clearly label the source of each log sample and the denominator of the metrics. If all errors are retained and only successful requests are sampled, the error rate in the logs is not the user failure rate. Use complete request counts or metrics with clear estimation methods to provide the denominator, and explain the sampling rationale. When changing the sampling rate, record the version number to avoid the appearance of a sudden increase in errors. When there is no complete evidence, report the sample range accurately and do not expand it to include all requests.

It’s important to consider the chronological order of events across different regions, not just the completion time.

Events originating from upstream processes may be logged earlier than the initiating events, capturing the sequence of network and batch processing changes. Events retain their timestamps, stages, and parent-child relationships, with timing determined by local monotonic timers. Even with synchronized clocks across machines, it’s not possible to precisely calculate network latency by simply subtracting the two wall clocks. A complete tracing system has its own timing model, while standard logging systems must acknowledge this limitation.

The caching process is completed after the response is returned from the backend. It can be associated with the originating request, but it is not part of the user’s response time. Logs should distinguish between synchronous and background tasks to avoid incorrectly counting cached writes as successful final requests. Failure of background tasks still affects subsequent resource consumption and hits, which can be observed independently. Associating helps to understand the cause and effect, but it does not mean that all connected events have the same business outcome.

User cancellations, application timeouts, and upstream rejections are treated separately. User cancellations are typically part of the normal lifecycle, while prolonged timeouts indicate a service issue. Authorization rejections may represent a security event or an unauthorized access attempt. Using only error levels is insufficient to describe these semantic differences. The limited number of categories makes it difficult to identify specific indicators, and the system retains only a small amount of security-related information for troubleshooting purposes, rather than treating all error messages as high-volume labels.

Temporary Diagnosis Expansion Requires an Exit Condition

To reproduce a specific parsing error, the maintainer may need to record a specific anonymized field. First, define the target route, sample range, responsible party, expiration date, and deletion policy, and then enable it. By default, it automatically expires. To extend the expiration date, you must re-specify the purpose to avoid long-term storage of excessive data after an incident. The original text should not be the fastest default option; instead, try to synthesize the input and use more precise categories.

The diagnostic switch cannot be enabled by standard request parameters, as this would allow an attacker to expand logs or leak data. Management actions require independent authorization, and the switch’s state can be observed. At the end, verify that the configuration is disabled and that new logs no longer contain extended fields. It is not sufficient to simply write “processed” in the event log. Old export files, screenshots, and local analysis tables also comply with access and retention policies. Leaving the platform does not mean that the information has been anonymized.

The whitelist must cover exceptions and the SDK. An error can cause the complete request object to be embedded, and generic serialization may bypass the main event’s de-identification. Testing should place fake tokens in multiple nested queries, headers, and third-party errors, ensuring that no original values are output in any public response or internal logs. Depth, length, and type rules control costs, while sensitive field projection controls information. Both are independently validated.

Resource Budget for Log Infrastructure Failures

When external collection is unavailable, there are upper limits on retries, buffering, and discarding. If each failed log entry results in another log entry indicating the same failure, this can create a recursive amplification. The decision of whether core business operations continue to rely on compliance and audit requirements will determine the appropriate approach. Generally, performance logs should not be so voluminous that they cause widespread crashes for public consumption, but critical audit logs may require stricter policies. The article should clearly state the trade-offs, and should not claim that logs are always optional.

Record the number and reasons for discarding messages in the buffer queue, but do not indefinitely retain the message content while waiting for recovery. After recovery, check for any concentrated sending peaks and, if necessary, perform controlled emptying. The persistence, sampling frequency, and retention duration of platform logs should be based on actual capabilities. A successful console call does not guarantee that the event can be permanently queried; verification requires retrieving and synthesizing samples.

Log correlation should also avoid user-controlled IDs from confusing different events. After external identifier validation, the IDs generated by this site still provide a unique range for the current request as external fields. Two requests using the same external value should not be misinterpreted by the dashboard as a single task. Client IDs support investigative intent, while server IDs support executing facts. The names and query examples should all express this distinction. Correlation identifiers are not authentication evidence and should not allow visitors who obtain the IDs to anonymously read internal events.

Accepting Changes and Generating Alerts Simultaneously

Changing upstreamStatus to upstream_status affects not only the code, but also the saving of queries, dashboards, and alerts. The migration list includes consumers, offering limited compatibility or one-time updates, and the synthetic failure proof alert can still identify failures. Do not directly change the error category for better charts without migrating historical comparisons. Natural language fields can be improved, and machine fact names should be stable or have a clear version.

The recovery drill progresses from the initial failure to the point where recovery, error rate reduction, and alarm disabling are achieved. Simply disabling the alarm does not guarantee that the interface is functioning correctly; it must be validated in conjunction with user tasks and content sample verification. Ultimately, the ability to answer questions such as: Which release, which stage, what impact, and what is the next action, without needing to know user secrets, is the true standard of log quality.

Validating Log Quality Through Fault Injection Exercises

Initiate triggering of upstream 500, timeouts, invalid JSON, and missing configurations. Verify that the event can be distinguished and that the associated ID is consistent. Test de-identification and structure with a fake email, fake token, and newline text. The original values should not appear in the logs. Check log query permissions and retention periods to prevent the observable system from becoming a new data outlet.

The final validation log failure will not cause normal requests to crash, nor will it create an infinite recursion error. Observability is a part of product reliability, but it must also have associated costs and security boundaries. Each log field should be able to indicate which troubleshooting action it supports.

Retrying the collection process may also result in duplicate events. A synthetic request should only fail once, and the collector should send the same event twice. If queries are based on log line counts, this can amplify the impact. To ensure stable event IDs for logical events, or to use platform-supported de-duplication methods, the event ID should be separate from the request ID: a single request can legitimately generate multiple stage events. Testing involves re-sending the same event and re-sending another stage of the same request. The first re-send can identify the duplicate, while the second re-send cannot be mistakenly deleted.

Not all platforms perform deduplication, and therefore, you cannot claim that the logs contain exactly one delivery event. The definition of the number of original events and logical events is maintained, and user impact continues to be supported by appropriate, complete counts. This example highlights the problem of treating query actions as business actions; before examining ten identical errors, it’s important to confirm that they represent ten separate executions, rather than a single failure that has been retried multiple times.

References: Worker Observability, OWASP Logging.