MiniApp Log Collection¶
The MiniApp Logs SDK sends business logs to TrueWatch and automatically collects console, runtime, and network errors. Logs are written to the browser_log source and can be searched in the Log Explorer. When used together with the MiniApp RUM SDK, logs can be associated with application, session, page, and user information.
This document describes the integration method and behavior based on SDK 1.0.6. For version changes, see the SDK changelog.
Getting Started¶
1. Install and Import¶
It is recommended to install via npm and use the datafluxLogs entry:
Import the SDK at the application entry point and initialize it before business logs and requests occur. When using native mini app development tools, complete the npm build as required by the tool.
You can also download the SDK file, place it in the mini app project, and import it from a local path. Adjust the path below to the actual file location:
The SDK automatically selects the available wx, my, swan, tt, or uni request APIs, which correspond to WeChat, Alipay, Baidu, Douyin, and uni hosts, respectively. When multiple APIs are available, they are selected in the order above. In a uni project, import and initialize the SDK in the mini app-side code. Device, network, storage, or lifecycle APIs degrade independently when unavailable; if no request API is available, no logs are collected and an initialization notice is printed.
The SDK runs in the mini app host, and the install package does not set an engines.node restriction. Node.js is used only for build, test, and release tooling during development, and its version must satisfy the requirements of the corresponding development dependencies.
2. Initialization¶
Choose one reporting method and initialize once within the application lifecycle. The reporting endpoint must be accessible from the mini app, and the request domain must be configured as required by the target platform.
Configure an accessible DataKit endpoint. Set datakitOrigin to the protocol, domain or IP, and an optional port. Do not append /v1/write/logging.
datafluxLogs.init({
datakitOrigin: 'https://datakit.example.com',
applicationId: '<APPLICATION_ID>',
service: 'miniapp',
env: 'prod',
version: '1.0.0'
})
applicationId identifies the application and can be set as needed. For DataKit deployment and network configuration, see DataKit tools documentation.
Obtain the site URL and client token from the TrueWatch console, and configure site and clientToken. This method does not require datakitOrigin.
Calling init() again does not update the configuration. silentMultipleInit: true only disables the repeated-initialization notice.
3. Send and View Logs¶
After initialization, use datafluxLogs in the same module; other pages can import the same SDK module as described above.
datafluxLogs.logger.info('应用启动', { entry: 'home' })
datafluxLogs.logger.warn('库存不足', { product_id: 'product-123' })
datafluxLogs.logger.error('支付失败', { order_id: 'order-123' })
Logs are sent in batches. By default, an attempt is made every 30 seconds; sending is also triggered when the batch threshold is reached or the application enters the background. Go to the Log Explorer and search by source browser_log, service, log message, or custom fields.
Configuration¶
Initialization Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
datakitOrigin |
String | — | DataKit reporting endpoint; when using DataKit, provide at least this parameter or datakitUrl, with this parameter taking precedence. |
datakitUrl |
String | — | Compatibility alias for datakitOrigin. |
site |
String | — | Public DataWay reporting endpoint; required when using Public DataWay. |
clientToken |
String | — | Public DataWay client token; used together with site and cannot be empty. |
applicationId |
String | — | Application ID when Logs is used standalone, corresponding to app_id; when associated with RUM, the RUM application context at the time the log occurred is used. |
service |
String | miniapp |
Service name to which the logs belong. |
env |
String | Empty string | Application environment, such as prod, pre, local. |
version |
String | Empty string | Business application version number, distinct from the SDK package version. |
sampleRate |
Number | 100 |
Session sampling rate for HTTP log reporting, from 0 to 100. 0 disables reporting; 100 reports all logs. |
forwardErrorsToLogs |
Boolean | true |
Whether to automatically collect console, runtime, and network errors; setting it to false does not affect manual log APIs. |
rumIntakeUrls |
String[] | [] |
Optional. Additional full RUM upload URLs to exclude from automatic network error collection, for cases where RUM and Logs use different intake endpoints. |
silentMultipleInit |
Boolean | false |
Whether to disable the repeated-initialization notice; this does not change the initialization result. |
All parameters other than the endpoint and token required by the selected reporting method are optional. Sampling is determined at SDK initialization and the result applies throughout the same runtime instance; it is not an independent random sample for each log.
Starting from 1.0.6, the unimplemented initialization options tags, trackInteractions, allowedTracingOrigins, traceId128Bit, and traceType have been removed. Use the context API for custom fields; interaction and trace collection are configured in the RUM SDK.
Usage¶
Log Levels¶
The default Logger is datafluxLogs.logger, with a default level of debug and HTTP reporting by default. You can call the corresponding methods directly:
| Method | Log status |
Example use |
|---|---|---|
logger.debug(message, context) |
debug |
Debugging information. |
logger.info(message, context) |
info |
Business events and runtime information. |
logger.warn(message, context) |
warning |
Recoverable exceptions or business alerts. |
logger.error(message, context) |
error |
Business failures or errors. |
logger.critical(message, context) |
critical |
Critical errors. |
message is a string, and context is an optional field object. You can also use log(message, context, status) to explicitly specify the level; when status is omitted, the level is info. Note that the status value for warn() is warning:
Use setLevel() to set the minimum level; logs below that level are not emitted. The level order is debug → info → warning → error → critical:
Custom Logger¶
Create Loggers for different business modules, with level, output handler, and persistent context set separately:
const paymentLogger = datafluxLogs.createLogger('payment', {
level: 'info',
handler: 'http',
context: { module: 'payment' }
})
paymentLogger.info('创建订单', { order_id: 'order-123' })
createLogger(name, configuration) returns the created Logger; you can later retrieve it with getLogger(name). A name that has not been created returns undefined. The level, handler, and context fields in configuration can all be omitted; they default to debug, http, and an empty object, respectively.
Use setHandler() to switch the output handler:
handler |
Behavior |
|---|---|
http |
Reports logs in batches via the SDK. |
console |
Calls console.log to output the level, message, and Logger/per-log context, without HTTP reporting. |
silent |
Does not output logs from this Logger. |
const paymentLogger = datafluxLogs.getLogger('payment')
if (paymentLogger) {
paymentLogger.setHandler('console')
}
Automatically collected errors are emitted by the default Logger. Therefore, changing the level or output handler of datafluxLogs.logger also affects automatic error logs. Settings on a named Logger apply only to that Logger.
Custom Fields¶
Custom fields can be placed in the global context, Logger context, or per-log context. When reporting over HTTP, custom fields with the same name are overridden in the order global → Logger → per-log.
Global context applies to HTTP logs of all Loggers:
datafluxLogs.setLoggerGlobalContext({ tenant: 'example' })
datafluxLogs.addLoggerGlobalContext('region', 'cn')
const globalContext = datafluxLogs.getLoggerGlobalContext()
datafluxLogs.removeLoggerGlobalContext('region')
Logger context applies only to the corresponding Logger:
datafluxLogs.logger.setContext({ team: 'payments' })
datafluxLogs.logger.addContext('channel', 'miniapp')
datafluxLogs.logger.removeContext('channel')
setLoggerGlobalContext() and setContext() replace the entire corresponding context; add...Context() adds or replaces a single field, and remove...Context() removes a field. Getting the global context returns an independent snapshot; modifying the returned object does not change the data stored inside the SDK.
Per-log context applies only to the current call:
datafluxLogs.logger.info('支付完成', {
order_id: 'order-123',
amount: 0,
paid: true,
customer: { id: 'customer-123' },
items: ['product-123']
})
Fields support scalars, objects, and arrays. Valid values such as 0 and false are preserved; objects and arrays are serialized to JSON strings when reported, and BigInt is sent as an exact decimal string. Regular business fields can be placed directly at the root level of the context; the tags: { ... } syntax is also supported, and this tags is ultimately sent as custom log fields.
Contexts use independent snapshots. Objects with a toJSON(key) method are serialized on the original instance using the actual field names, and the result is then stored, supporting redactors with private fields. If the redactor for a regular field fails, an error placeholder value is used, with no fallback to the unredacted original object.
For HTTP logs, the root context and nested tags accept only dictionary results; invalid results are ignored and valid persistent fields are retained. When setting persistent context, if the root redactor fails or returns a non-dictionary, the context is reset to an empty dictionary. Per-log calls do not modify persistent context.
Business fields should avoid using the same names as standard fields such as message, status, and service; business data with the same name can be placed in the business object. message and status are determined by the log call arguments, and type is fixed to the SDK's internal log type and cannot be replaced through context.
Manually Record Errors¶
logger.error() accepts a message and context. To record the stack of an Error, place it explicitly in error.stack:
const error = new Error('支付接口超时')
datafluxLogs.logger.error(error.message, {
order_id: 'order-123',
error: { stack: error.stack }
})
Manual errors are reported with error_source=logger by default. An explicit error.source passed in a single log can override the default source; automatic errors retain their actual source.
Automatic Error Collection¶
Enabled by default; you can disable it with forwardErrorsToLogs: false. Collection capabilities depend on the APIs provided by the host:
| Source | Collected content |
|---|---|
| Console | Message and arguments of console.error(); console.log(), info(), or warn() are not collected automatically. |
| Runtime | Host error events, unhandled Promise rejections, and, where supported, page-not-found and memory warning events. |
| Network | Network failures of request and downloadFile, and responses with HTTP status codes greater than or equal to 500, subject to the callback scope described below. |
Automatic network error collection requires the business call to provide a success, fail, or complete callback and to use a plain argument object that can be safely copied. Frozen objects, null-prototype dictionaries, non-enumerable data properties, Symbol metadata, and valid values of reactive Proxies can be preserved; the original callback arguments, return values, exceptions, and native task/Promise objects remain unchanged.
The following cases do not automatically generate a request completion log:
- The call does not provide any callback. The SDK does not inject callbacks or read or subscribe to business Promises, preserving the original return pattern and unhandled rejection events.
- The arguments contain accessors or special prototypes. The SDK passes the original arguments to the host, preserving the original read behavior.
- The request is to Logs' own or an excluded RUM upload URL.
HTTP 4xx responses do not generate error logs based on status code alone. Failures already caught by the business can be recorded manually with logger.error(); unhandled rejections can still be collected by the host runtime hook. Response bodies are not read for successful requests or excluded upload requests.
RUM Association¶
Logs can be used standalone. To associate user access context, initialize the RUM SDK as described in the MiniApp RUM integration documentation. When RUM context is available, logs carry the corresponding application, session, page, action, and user information; when it is unavailable, standalone logs can still be reported.
The SDK retrieves the RUM context at the time the log occurred. For delayed errors, when historical data is missing or stale, the corresponding fields are omitted rather than replaced with the current page. Without RUM association, regular immediate logs can still carry the current page route, but they do not create a RUM page ID on their own.
Logs automatically excludes its own upload URL and /v1/write/rum under the same intake endpoint. If RUM and Logs use different domains, ports, or proxy paths, set the optional rumIntakeUrls to prevent mutual collection when uploads fail:
datafluxLogs.init({
datakitOrigin: 'https://logs.example.com',
rumIntakeUrls: ['https://rum.example.com/v1/write/rum']
})
This configuration should be merged into the initial init() call; do not reinitialize. The list accepts only full HTTP(S) URLs; a snapshot is stored at initialization, and invalid entries are ignored. Comparison normalizes the protocol, hostname case, and default ports, ignores query/fragment, and preserves the full path and its case; other business paths under the same domain are not excluded.
Reported Fields¶
Log methods such as logger.log() return void and do not return a log object. The SDK writes data to the browser_log source. The following are commonly used fields in the Log Explorer, not a fixed nested JSON return structure.
| Field | Content |
|---|---|
message, status, service |
Message, level, and service name. |
sdk_name, sdk_version |
SDK name and package version. |
app_id, env, version |
Application ID, environment, and business version. |
session_id |
Logs session identifier; when associated with RUM, its session information is used. |
view_id, view_name, view_referer, action_id |
Available page, referrer page, and action information; view_name corresponds to the page route. |
userid, user_name, user_email |
User information available in the RUM context. |
platform, platform_version, app_framework_version |
Mini app host type, host version, and base library version. |
device, model, device_uuid, os, os_version, network_type |
Device brand, model, anonymous installation identifier, operating system, and network information. |
error_source, error_type, error_stack |
Error source, type, and stack; provided according to the actual error content. |
error_resource_url, error_resource_method, error_resource_status |
Request URL, method, and status code for the network error. |
| Custom fields | For example order_id, amount, paid; valid values are preserved when writing. Avoid using the same names as standard fields. |
platform indicates the mini app host; the operating system uses separate fields such as os. device_uuid is an anonymous installation identifier generated by the SDK and saved to local storage. It is not a host AppID or hardware ID. It is regenerated when storage is cleared, and when storage is unavailable, it is stable only for the current runtime.
Reporting Timing and Limits¶
| Behavior | Description |
|---|---|
| Periodic sending | By default, cached logs are sent every 30 seconds. |
| Batch sending | Sends early when the batch threshold of 50 entries or about 16 KiB is reached. |
| Background sending | When the host supports onAppHide, sending is triggered when the application enters the background. |
| Single-entry size | A single serialized log must be smaller than 256 KiB; entries exceeding the limit are dropped. |
| Error rate limit | A single SDK instance reports at most 3000 logs with status=error within a one-minute window; beyond this, a rate-limit notice is additionally recorded, and reporting resumes after the window resets. |
| Sending failures | Logs are delivered on a best-effort basis; no local persistent queue, automatic retry on failure, or delivery guarantee is provided. |
These are the SDK's built-in sending behaviors, not public initialization options. Large objects or response bodies increase the size of individual logs; it is recommended to record only the business fields needed for troubleshooting.
FAQ¶
| Symptom | Check |
|---|---|
| No logs after initialization | Check the endpoint and token, request domain, and network; confirm that the SDK was initialized before business calls, sampleRate is not 0, the Logger level allows the log, and the handler is http. Wait for the periodic send, or trigger sending by switching to the background when the host supports it. |
| Console has output but the log platform has no records | Check whether handler: 'console' is in use; regular console.log() calls are not reported automatically. |
| Promise request failures produce no network logs | Check whether the call has no callbacks or the error has been caught by the business; call logger.error() explicitly if needed. |
| Errors are not associated with a RUM page | Check whether RUM has been initialized and whether the context at the corresponding time exists; standalone Logs logs do not automatically create RUM page records. |
| Type errors appear in configuration options after upgrade | Refer to the initialization parameters table and remove the unimplemented options; add custom fields through the context API. |
SDK Changelog¶
1.0.6 (2026-09-09)¶
Features and Compatibility¶
- Improved automatic detection for WeChat, Alipay, Baidu, Douyin, and uni hosts, as well as compatibility handling for device, network, storage, and lifecycle APIs; safe degradation when optional APIs are unavailable.
- When Logs is used standalone, the application ID can be reported via
applicationId; when associated with RUM, the context is retrieved at the time the log occurred, preventing delayed errors from being associated with the current page or session. - Added the optional
rumIntakeUrlsto exclude RUM uploads at separate intake endpoints; Logs/RUM uploads under the same intake endpoint are excluded automatically, preventing mutual collection after upload failures. - Completed public TypeScript declarations and type entries in the published package; removed the
engines.nodeinstallation restriction, as the SDK does not depend on Node.js at runtime. Repository build, test, and release tooling must still meet the Node.js requirements of each development dependency.
Bug Fixes¶
- Fixed the impact of request and download interception on original arguments, business callbacks, returned task/Promise objects, and unhandled rejection events; valid values of reactive arguments are preserved, and collection exceptions no longer affect business calls. Response bodies are no longer read for successful requests and excluded upload requests.
- Fixed context tampering, dangerous property merging, and incorrect reuse of redaction results;
toJSON(key)is executed on the original object using the actual field names and an independent snapshot is stored, supporting redactors with private fields, objects, arrays, and BigInt. - Fixed issues where a non-dictionary result or redaction failure in the root context and nested
tagsproduced numeric fields or dropped existing fields; invalid contexts do not fall back to unredacted original values, and per-log calls do not modify persistent context. - Fixed loss of multi-line messages, original stacks, and network diagnostic fields for runtime errors and unhandled rejections; manual error logs are correctly reported with the default source
logger, while automatic errors retain their actual source. - Fixed escaping of reported fields, Unicode byte counting, loss of valid values such as
0/false, and batch reentry issues; logs are flushed promptly when the application enters the background.platformcorrectly represents the host, anddevice_uuiduses the locally persisted anonymous installation identifier.
Upgrade Notes¶
- Removed the unimplemented initialization options
tags,trackInteractions,allowedTracingOrigins,traceId128Bit, andtraceType; use the context API for custom fields, and interaction and trace collection are configured by the RUM SDK. - Callback-less calls, as well as request arguments containing accessors or special prototypes, retain the host's original behavior and do not automatically generate request completion logs; failures already caught by the business can be recorded manually with
logger.error(), and unhandled rejections can still be collected by the host runtime hook.