|
| 1 | +/* |
| 2 | + * Copyright 2025 Adobe. All rights reserved. |
| 3 | + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | + * of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + * |
| 7 | + * Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | + * OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | + * governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | +/* eslint-env serviceworker */ |
| 13 | + |
| 14 | +/** |
| 15 | + * Normalizes log input to always be an object. |
| 16 | + * Converts string inputs to { message: string } format. |
| 17 | + * @param {*} data - The log data (string or object) |
| 18 | + * @returns {object} Normalized log object |
| 19 | + */ |
| 20 | +export function normalizeLogData(data) { |
| 21 | + if (typeof data === 'string') { |
| 22 | + return { message: data }; |
| 23 | + } |
| 24 | + if (typeof data === 'object' && data !== null) { |
| 25 | + return { ...data }; |
| 26 | + } |
| 27 | + return { message: String(data) }; |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Enriches log data with context metadata. |
| 32 | + * @param {object} data - The log data object |
| 33 | + * @param {string} level - The log level (debug, info, warn, error) |
| 34 | + * @param {object} context - The context object with metadata |
| 35 | + * @returns {object} Enriched log object |
| 36 | + */ |
| 37 | +export function enrichLogData(data, level, context) { |
| 38 | + return { |
| 39 | + timestamp: new Date().toISOString(), |
| 40 | + level, |
| 41 | + requestId: context.invocation?.requestId, |
| 42 | + transactionId: context.invocation?.transactionId, |
| 43 | + functionName: context.func?.name, |
| 44 | + functionVersion: context.func?.version, |
| 45 | + functionFQN: context.func?.fqn, |
| 46 | + region: context.runtime?.region, |
| 47 | + ...data, |
| 48 | + }; |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Creates a logger instance for Fastly using fastly:logger module. |
| 53 | + * Uses async import and handles initialization. |
| 54 | + * Dynamically checks context.attributes.loggers on each call. |
| 55 | + * @param {object} context - The context object |
| 56 | + * @returns {object} Logger instance with level methods |
| 57 | + */ |
| 58 | +export function createFastlyLogger(context) { |
| 59 | + const loggers = {}; |
| 60 | + let loggersReady = false; |
| 61 | + let loggerPromise = null; |
| 62 | + let loggerModule = null; |
| 63 | + |
| 64 | + // Initialize Fastly logger module asynchronously |
| 65 | + // eslint-disable-next-line import/no-unresolved |
| 66 | + loggerPromise = import('fastly:logger').then((module) => { |
| 67 | + loggerModule = module; |
| 68 | + loggersReady = true; |
| 69 | + loggerPromise = null; |
| 70 | + }).catch((err) => { |
| 71 | + // eslint-disable-next-line no-console |
| 72 | + console.error(`Failed to import fastly:logger: ${err.message}`); |
| 73 | + loggersReady = true; |
| 74 | + loggerPromise = null; |
| 75 | + }); |
| 76 | + |
| 77 | + /** |
| 78 | + * Gets or creates logger instances for configured targets. |
| 79 | + * @param {string[]} loggerNames - Array of logger endpoint names |
| 80 | + * @returns {object[]} Array of logger instances |
| 81 | + */ |
| 82 | + const getLoggers = (loggerNames) => { |
| 83 | + if (!loggerNames || loggerNames.length === 0) { |
| 84 | + return []; |
| 85 | + } |
| 86 | + |
| 87 | + const instances = []; |
| 88 | + loggerNames.forEach((name) => { |
| 89 | + if (!loggers[name]) { |
| 90 | + try { |
| 91 | + loggers[name] = new loggerModule.Logger(name); |
| 92 | + } catch (err) { |
| 93 | + // eslint-disable-next-line no-console |
| 94 | + console.error(`Failed to create Fastly logger "${name}": ${err.message}`); |
| 95 | + return; |
| 96 | + } |
| 97 | + } |
| 98 | + instances.push(loggers[name]); |
| 99 | + }); |
| 100 | + return instances; |
| 101 | + }; |
| 102 | + |
| 103 | + /** |
| 104 | + * Sends a log entry to all configured Fastly loggers. |
| 105 | + * Dynamically checks context.attributes.loggers on each call. |
| 106 | + * @param {string} level - Log level |
| 107 | + * @param {*} data - Log data |
| 108 | + */ |
| 109 | + const log = (level, data) => { |
| 110 | + const normalizedData = normalizeLogData(data); |
| 111 | + const enrichedData = enrichLogData(normalizedData, level, context); |
| 112 | + const logEntry = JSON.stringify(enrichedData); |
| 113 | + |
| 114 | + // Get current logger configuration from context |
| 115 | + const loggerNames = context.attributes?.loggers; |
| 116 | + |
| 117 | + // If loggers are still initializing, wait for them |
| 118 | + if (loggerPromise) { |
| 119 | + loggerPromise.then(() => { |
| 120 | + const currentLoggers = getLoggers(loggerNames); |
| 121 | + if (currentLoggers.length > 0) { |
| 122 | + currentLoggers.forEach((logger) => { |
| 123 | + try { |
| 124 | + logger.log(logEntry); |
| 125 | + } catch (err) { |
| 126 | + // eslint-disable-next-line no-console |
| 127 | + console.error(`Failed to log to Fastly logger: ${err.message}`); |
| 128 | + } |
| 129 | + }); |
| 130 | + } else { |
| 131 | + // Fallback to console if no loggers configured |
| 132 | + // eslint-disable-next-line no-console |
| 133 | + console.log(logEntry); |
| 134 | + } |
| 135 | + }); |
| 136 | + } else if (loggersReady) { |
| 137 | + const currentLoggers = getLoggers(loggerNames); |
| 138 | + if (currentLoggers.length > 0) { |
| 139 | + currentLoggers.forEach((logger) => { |
| 140 | + try { |
| 141 | + logger.log(logEntry); |
| 142 | + } catch (err) { |
| 143 | + // eslint-disable-next-line no-console |
| 144 | + console.error(`Failed to log to Fastly logger: ${err.message}`); |
| 145 | + } |
| 146 | + }); |
| 147 | + } else { |
| 148 | + // Fallback to console if no loggers configured |
| 149 | + // eslint-disable-next-line no-console |
| 150 | + console.log(logEntry); |
| 151 | + } |
| 152 | + } |
| 153 | + }; |
| 154 | + |
| 155 | + return { |
| 156 | + fatal: (data) => log('fatal', data), |
| 157 | + error: (data) => log('error', data), |
| 158 | + warn: (data) => log('warn', data), |
| 159 | + info: (data) => log('info', data), |
| 160 | + verbose: (data) => log('verbose', data), |
| 161 | + debug: (data) => log('debug', data), |
| 162 | + silly: (data) => log('silly', data), |
| 163 | + }; |
| 164 | +} |
| 165 | + |
| 166 | +/** |
| 167 | + * Creates a logger instance for Cloudflare that emits console logs |
| 168 | + * using tab-separated format for efficient tail worker filtering. |
| 169 | + * Format: target\tlevel\tjson_body |
| 170 | + * Dynamically checks context.attributes.loggers on each call. |
| 171 | + * @param {object} context - The context object |
| 172 | + * @returns {object} Logger instance with level methods |
| 173 | + */ |
| 174 | +export function createCloudflareLogger(context) { |
| 175 | + /** |
| 176 | + * Sends a log entry to console for each configured target. |
| 177 | + * Uses tab-separated format: target\tlevel\tjson_body |
| 178 | + * This allows tail workers to efficiently filter without parsing JSON. |
| 179 | + * @param {string} level - Log level |
| 180 | + * @param {*} data - Log data |
| 181 | + */ |
| 182 | + const log = (level, data) => { |
| 183 | + const normalizedData = normalizeLogData(data); |
| 184 | + const enrichedData = enrichLogData(normalizedData, level, context); |
| 185 | + const body = JSON.stringify(enrichedData); |
| 186 | + |
| 187 | + // Get current logger configuration from context |
| 188 | + const loggerNames = context.attributes?.loggers; |
| 189 | + |
| 190 | + if (loggerNames && loggerNames.length > 0) { |
| 191 | + // Emit one log per target using tab-separated format |
| 192 | + // Format: target\tlevel\tjson_body |
| 193 | + loggerNames.forEach((target) => { |
| 194 | + // eslint-disable-next-line no-console |
| 195 | + console.log(`${target}\t${level}\t${body}`); |
| 196 | + }); |
| 197 | + } else { |
| 198 | + // No targets configured, emit without target prefix |
| 199 | + // eslint-disable-next-line no-console |
| 200 | + console.log(`-\t${level}\t${body}`); |
| 201 | + } |
| 202 | + }; |
| 203 | + |
| 204 | + return { |
| 205 | + fatal: (data) => log('fatal', data), |
| 206 | + error: (data) => log('error', data), |
| 207 | + warn: (data) => log('warn', data), |
| 208 | + info: (data) => log('info', data), |
| 209 | + verbose: (data) => log('verbose', data), |
| 210 | + debug: (data) => log('debug', data), |
| 211 | + silly: (data) => log('silly', data), |
| 212 | + }; |
| 213 | +} |
0 commit comments