Skip to content

Analytics Transports ​

The Mixpanel, Segment and Google Analytics transports turn log entries into product-analytics events. They share one batching base with the Datadog transport, so most behavior below applies to all of them.

Configure them under transports.analytics. Each key takes one config or an array.

ts
import { createLogger } from 'logixia';

const logger = createLogger({
  appName: 'web',
  transports: {
    analytics: {
      mixpanel: { apiKey: '', token: process.env.MIXPANEL_TOKEN! },
      segment: { apiKey: '', writeKey: process.env.SEGMENT_WRITE_KEY! },
      googleAnalytics: {
        apiKey: '',
        measurementId: process.env.GA_MEASUREMENT_ID!,
        apiSecret: process.env.GA_API_SECRET!,
      },
    },
  },
});

WARNING

The shared analytics config type requires an apiKey string on every provider, but Mixpanel, Segment and Google Analytics do not read it. They use token, writeKey and apiSecret. Pass an empty string for apiKey to satisfy the type. Only Datadog uses apiKey.

Shared behavior ​

OptionTypeDefaultDescription
batchSizenumber50Entries collected before a send. A value of 1 or less sends each entry straight away.
flushIntervalnumber (ms)10000Send whatever is buffered after this long.
maxBufferSizenumber10000Most entries held while the provider is unreachable. Past it the oldest are dropped and counted. Never below batchSize.
customPropertiesRecord<string, unknown>unsetExtra properties merged into every event.
levelstringunsetMinimum level for this transport.
filter(entry) => booleanunsetReturn false to skip an entry on this transport.
endpointstringprovider defaultUsed by Mixpanel only.
enableUserTrackingbooleantrueGates Mixpanel's identifyUser and setUserProperties.
enableEventTrackingbooleantrueGates Mixpanel's trackCustomEvent.

What every analytics transport does:

  • Skips debug and trace entries. They are never sent.
  • Validates its config on the first write. A missing token or key makes every write fail with the same error instead of crashing at startup.
  • Re-buffers failures. A failed batch goes back to the front of the buffer and the flush stops until the next timer tick or threshold. Datadog resends only the part of a batch that was not delivered.
  • Keeps your fields from overwriting core fields. A payload key that clashes with a core field or a provider-reserved name is stored with a data_ prefix.
  • Closes cleanly. close() tries up to three flushes, then reports what could not be sent.

Mixpanel ​

Events are named log_<level> (for example log_error) and posted to https://api.mixpanel.com/track.

ts
import { createLogger } from 'logixia';

const logger = createLogger({
  appName: 'web',
  transports: {
    analytics: {
      mixpanel: {
        apiKey: '',
        token: process.env.MIXPANEL_TOKEN!,
        distinct_id: 'service-account',
        enableSuperProperties: true,
        superProperties: { platform: 'web' },
      },
    },
  },
});
OptionTypeDefaultDescription
tokenstringrequiredMixpanel project token.
distinct_idstring'anonymous'distinct_id on every event.
enableSuperPropertiesbooleanoffMerge superProperties into every event.
superPropertiesRecord<string, unknown>unsetProperties added when enableSuperProperties is on.
endpointstringhttps://api.mixpanel.comAPI base URL, for example an EU or proxy endpoint.

Each event gets time (milliseconds), a $insert_id built from the timestamp, message and trace ID so retries do not create duplicates, plus the entry fields and your payload. token, distinct_id, time and $insert_id are reserved. Mixpanel answers 1 on success; any other reply is treated as an error.

Helpers on the class: identifyUser({ id, properties }), setUserProperties(userId, properties) and trackCustomEvent(name, properties).

Segment ​

Events are named Log <Level> (for example Log Error) and sent to /v1/batch, or /v1/track when batching is off. The write key is sent with Basic auth.

ts
import { createLogger } from 'logixia';

const logger = createLogger({
  appName: 'web',
  transports: {
    analytics: {
      segment: {
        apiKey: '',
        writeKey: process.env.SEGMENT_WRITE_KEY!,
        userIdField: 'userId',
        maxBatchSize: 100,
      },
    },
  },
});

await logger.info('Plan upgraded', { userId: 'u_42', plan: 'pro' });
OptionTypeDefaultDescription
writeKeystringrequiredSegment write key.
dataPlaneUrlstringhttps://api.segment.ioAPI base URL, for example a regional or proxy endpoint.
userIdFieldstring'userId'Payload field read as the Segment userId. Only string values are used.
enableBatchingbooleantrueSend many events in one /v1/batch call. If false, entries are sent one by one.
maxBatchSizenumber100Events per /v1/batch request.
flushIntervalnumber (ms)10000Same as the shared option.
flushAtnumbernoneDeclared in the type but not used. Use batchSize to control when a send starts.

Each event carries a random anonymousId, the entry fields as properties, and a context.library of logixia. When the entry has a trace ID, it is also put in context.trace.trace_id. logger is a reserved property name.

Helpers on the class: identify, page, screen, group, alias, trackCustomEvent, trackPurchase and trackProductViewed.

Google Analytics 4 ​

Entries are sent as log_event events through the GA4 Measurement Protocol, up to 25 events per request.

ts
import { createLogger } from 'logixia';

const logger = createLogger({
  appName: 'web',
  transports: {
    analytics: {
      googleAnalytics: {
        apiKey: '',
        measurementId: process.env.GA_MEASUREMENT_ID!,
        apiSecret: process.env.GA_API_SECRET!,
        clientId: 'server-1',
      },
    },
  },
});
OptionTypeDefaultDescription
measurementIdstringrequiredGA4 measurement ID, such as G-XXXXXXX.
apiSecretstringrequiredMeasurement Protocol API secret.
clientIdstringrandom per requestGA4 client_id.
enableEnhancedMeasurementbooleanoffEnables the trackFileDownload and trackVideoEngagement helpers.
enableEcommercebooleannoneDeclared in the type but not used.

Event parameters include event_category (from the level), event_label and log_message (the message), log_level, timestamp, trace_id, app_name, environment and three custom dimensions (level, context, environment). Your payload is flattened into parent_child keys, and every value is converted to a string and cut to 100 characters to fit GA4 limits. Those parameter names are reserved.

Helpers on the class include trackPageView, trackCustomEvent, trackConversion, trackError and setUserProperties.

Released under the MIT License.