|
| 1 | +/* |
| 2 | + * Copyright (c) 2025, Salesforce, Inc. |
| 3 | + * SPDX-License-Identifier: Apache-2 |
| 4 | + * For full license text, see the license.txt file in the repo root or http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | + */ |
| 6 | +import {Flags, ux} from '@oclif/core'; |
| 7 | +import {MrtCommand} from '@salesforce/b2c-tooling-sdk/cli'; |
| 8 | +import {getProfile, tailMrtLogs, type MrtLogEntry} from '@salesforce/b2c-tooling-sdk/operations/mrt'; |
| 9 | +import {t} from '../../i18n/index.js'; |
| 10 | +import {formatMrtEntry, colorLevel, colorHighlight} from '../../utils/mrt-logs/index.js'; |
| 11 | + |
| 12 | +export default class MrtTailLogs extends MrtCommand<typeof MrtTailLogs> { |
| 13 | + static description = t( |
| 14 | + 'commands.mrt.tail-logs.description', |
| 15 | + 'Tail application logs from a Managed Runtime environment', |
| 16 | + ); |
| 17 | + |
| 18 | + static enableJsonFlag = true; |
| 19 | + |
| 20 | + static examples = [ |
| 21 | + '<%= config.bin %> <%= command.id %> -p my-storefront -e staging', |
| 22 | + '<%= config.bin %> <%= command.id %> -p my-storefront -e production --level ERROR --level WARN', |
| 23 | + '<%= config.bin %> <%= command.id %> -p my-storefront -e staging --json', |
| 24 | + '<%= config.bin %> <%= command.id %> -p my-storefront -e staging --search "timeout"', |
| 25 | + '<%= config.bin %> <%= command.id %> -p my-storefront -e staging --search "GET|POST"', |
| 26 | + ]; |
| 27 | + |
| 28 | + static flags = { |
| 29 | + ...MrtCommand.baseFlags, |
| 30 | + level: Flags.string({ |
| 31 | + description: 'Filter by log level (ERROR, WARN, INFO, DEBUG, etc.)', |
| 32 | + multiple: true, |
| 33 | + }), |
| 34 | + search: Flags.string({ |
| 35 | + char: 'g', |
| 36 | + description: 'Filter entries matching this regex pattern (case-insensitive)', |
| 37 | + }), |
| 38 | + 'no-color': Flags.boolean({ |
| 39 | + description: 'Disable colored output', |
| 40 | + default: false, |
| 41 | + }), |
| 42 | + }; |
| 43 | + |
| 44 | + async run(): Promise<void> { |
| 45 | + this.requireMrtCredentials(); |
| 46 | + |
| 47 | + const {mrtProject: project, mrtEnvironment: environment, mrtOrigin: origin} = this.resolvedConfig.values; |
| 48 | + |
| 49 | + if (!project) { |
| 50 | + this.error( |
| 51 | + 'MRT project is required. Provide --project flag, set SFCC_MRT_PROJECT, or set mrtProject in dw.json.', |
| 52 | + ); |
| 53 | + } |
| 54 | + if (!environment) { |
| 55 | + this.error( |
| 56 | + 'MRT environment is required. Provide --environment flag, set SFCC_MRT_ENVIRONMENT, or set mrtEnvironment in dw.json.', |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + const auth = this.getMrtAuth(); |
| 61 | + const useColor = !this.flags['no-color'] && process.stdout.isTTY && !this.jsonEnabled(); |
| 62 | + const levelFilter = this.flags.level; |
| 63 | + const searchFilter = this.flags.search; |
| 64 | + |
| 65 | + // Compile search regex (case-insensitive, global for highlighting) |
| 66 | + let searchRegex: RegExp | undefined; |
| 67 | + if (searchFilter) { |
| 68 | + try { |
| 69 | + searchRegex = new RegExp(searchFilter, 'gi'); |
| 70 | + } catch { |
| 71 | + this.error(`Invalid search pattern: "${searchFilter}". Must be a valid regular expression.`); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + // Pre-compute level filter set |
| 76 | + const upperLevels = levelFilter && levelFilter.length > 0 ? new Set(levelFilter.map((l) => l.toUpperCase())) : null; |
| 77 | + |
| 78 | + // Best-effort user email for WebSocket connection |
| 79 | + let user: string | undefined; |
| 80 | + try { |
| 81 | + const profile = await getProfile({origin}, auth); |
| 82 | + user = profile.email; |
| 83 | + } catch { |
| 84 | + // Non-fatal: proceed without user email |
| 85 | + } |
| 86 | + |
| 87 | + if (!this.jsonEnabled()) { |
| 88 | + this.log( |
| 89 | + t('commands.mrt.tail-logs.connecting', 'Connecting to {{project}}/{{environment}} logs...', { |
| 90 | + project, |
| 91 | + environment, |
| 92 | + }), |
| 93 | + ); |
| 94 | + |
| 95 | + // Log active filters |
| 96 | + if (upperLevels) { |
| 97 | + const levels = useColor ? [...upperLevels].map((l) => colorLevel(l)).join(', ') : [...upperLevels].join(', '); |
| 98 | + this.log(t('commands.mrt.tail-logs.filterLevel', 'Filtering by level: {{levels}}', {levels})); |
| 99 | + } |
| 100 | + if (searchFilter) { |
| 101 | + const pattern = useColor ? colorHighlight(searchFilter) : searchFilter; |
| 102 | + this.log(t('commands.mrt.tail-logs.filterSearch', 'Filtering by pattern: {{pattern}}', {pattern})); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + const {stop, done} = await tailMrtLogs( |
| 107 | + { |
| 108 | + projectSlug: project, |
| 109 | + environmentSlug: environment, |
| 110 | + origin, |
| 111 | + user, |
| 112 | + onEntry: (entry: MrtLogEntry) => { |
| 113 | + // Apply level filter |
| 114 | + if (upperLevels && (!entry.level || !upperLevels.has(entry.level.toUpperCase()))) return; |
| 115 | + |
| 116 | + // Apply search filter (regex match against message and raw) |
| 117 | + if (searchRegex) { |
| 118 | + // Reset lastIndex since we reuse the global regex |
| 119 | + searchRegex.lastIndex = 0; |
| 120 | + const matchesMessage = searchRegex.test(entry.message); |
| 121 | + searchRegex.lastIndex = 0; |
| 122 | + const matchesRaw = searchRegex.test(entry.raw); |
| 123 | + if (!matchesMessage && !matchesRaw) return; |
| 124 | + // Reset for highlighting pass |
| 125 | + searchRegex.lastIndex = 0; |
| 126 | + } |
| 127 | + |
| 128 | + if (this.jsonEnabled()) { |
| 129 | + ux.stdout(JSON.stringify(entry)); |
| 130 | + } else { |
| 131 | + ux.stdout(formatMrtEntry(entry, {useColor, searchHighlight: searchRegex})); |
| 132 | + } |
| 133 | + }, |
| 134 | + onConnect: () => { |
| 135 | + if (!this.jsonEnabled()) { |
| 136 | + this.log(t('commands.mrt.tail-logs.connected', 'Connected. Waiting for log entries...')); |
| 137 | + this.log(t('commands.mrt.tail-logs.interrupt', 'Press Ctrl+C to stop.\n')); |
| 138 | + } |
| 139 | + }, |
| 140 | + onError: (error: Error) => { |
| 141 | + this.warn(t('commands.mrt.tail-logs.error', 'WebSocket error: {{message}}', {message: error.message})); |
| 142 | + }, |
| 143 | + onClose: (_code: number, _reason: string) => { |
| 144 | + if (!this.jsonEnabled()) { |
| 145 | + this.log(t('commands.mrt.tail-logs.disconnected', '\nDisconnected from log stream.')); |
| 146 | + } |
| 147 | + }, |
| 148 | + }, |
| 149 | + auth, |
| 150 | + ); |
| 151 | + |
| 152 | + // Graceful shutdown on signals |
| 153 | + const handleSignal = (): void => { |
| 154 | + stop(); |
| 155 | + }; |
| 156 | + |
| 157 | + process.on('SIGINT', handleSignal); |
| 158 | + process.on('SIGTERM', handleSignal); |
| 159 | + |
| 160 | + await done; |
| 161 | + } |
| 162 | +} |
0 commit comments