forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate-logger.ts
More file actions
231 lines (198 loc) · 6.44 KB
/
Copy pathcreate-logger.ts
File metadata and controls
231 lines (198 loc) · 6.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { CLI_LOGS_DIR, CLI_SYSTEM_DIR, CONFIG_DIR } from '../../lib';
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';
export interface CreateLoggerOptions {
/** Project root directory (the new project being created) */
projectRoot: string;
}
interface StepInfo {
name: string;
startTime: number;
}
/**
* Structured logger for the create command.
* Creates log files in <projectRoot>/agentcore/.cli/logs/ with timestamped filenames.
* Tracks execution steps with timing and status information.
*/
export class CreateLogger {
readonly logFilePath: string;
private readonly startTime: Date;
private currentStep: StepInfo | null = null;
private initialized = false;
private pendingLines: string[] = [];
constructor(options: CreateLoggerOptions) {
this.startTime = new Date();
// Log file will be in <projectRoot>/agentcore/.cli/logs/create/create-TIMESTAMP.log
const logsDir = path.join(options.projectRoot, CONFIG_DIR, CLI_SYSTEM_DIR, CLI_LOGS_DIR, 'create');
const timestamp = this.formatTimestampForFilename(this.startTime);
this.logFilePath = path.join(logsDir, `create-${timestamp}.log`);
}
/**
* Initialize the log file. Call this after the config directory is created.
*/
initialize(): void {
if (this.initialized) return;
const logsDir = path.dirname(this.logFilePath);
// Ensure logs directory exists
if (!existsSync(logsDir)) {
mkdirSync(logsDir, { recursive: true });
}
// Write header
this.writeHeader();
this.initialized = true;
// Flush any pending lines
for (const line of this.pendingLines) {
appendFileSync(this.logFilePath, line + '\n', 'utf-8');
}
this.pendingLines = [];
}
/**
* Format a date for use in filename: YYYYMMDD-HHMMSS
*/
private formatTimestampForFilename(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}${month}${day}-${hours}${minutes}${seconds}`;
}
/**
* Format a date for log entries: HH:MM:SS
*/
private formatTime(date: Date = new Date()): string {
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
}
/**
* Format duration in human-readable form
*/
private formatDuration(ms: number): string {
if (ms < 1000) {
return `${ms}ms`;
}
const seconds = ms / 1000;
if (seconds < 60) {
return `${seconds.toFixed(1)}s`;
}
const minutes = Math.floor(seconds / 60);
const remainingSeconds = Math.round(seconds % 60);
return `${minutes}m ${remainingSeconds}s`;
}
/**
* Write the log file header
*/
private writeHeader(): void {
const separator = '='.repeat(80);
const header = `${separator}
AGENTCORE CREATE LOG
Started: ${this.startTime.toISOString()}
${separator}
`;
writeFileSync(this.logFilePath, header, 'utf-8');
}
/**
* Append a line to the log file (or queue it if not yet initialized)
*/
appendLine(line: string): void {
if (!this.initialized) {
this.pendingLines.push(line);
return;
}
appendFileSync(this.logFilePath, line + '\n', 'utf-8');
}
/**
* Mark the start of a step
*/
startStep(name: string): void {
// End previous step if any
if (this.currentStep) {
this.endStep('success');
}
this.currentStep = {
name,
startTime: Date.now(),
};
this.appendLine('');
this.appendLine(`[${this.formatTime()}] STEP: ${name}`);
}
/**
* Mark the end of the current step
*/
endStep(status: 'success' | 'error' | 'warn', error?: string): void {
if (!this.currentStep) {
return;
}
const duration = Date.now() - this.currentStep.startTime;
const statusText = status === 'success' ? 'SUCCESS' : status === 'warn' ? 'WARNING' : 'FAILED';
if ((status === 'error' || status === 'warn') && error) {
this.appendLine(`[${this.formatTime()}] ${status === 'error' ? 'Error' : 'Warning'}: ${error}`);
}
this.appendLine(`[${this.formatTime()}] Status: ${statusText}`);
this.appendLine(`[${this.formatTime()}] Duration: ${this.formatDuration(duration)}`);
this.currentStep = null;
}
/**
* Log a message with optional level
*/
log(message: string, level?: 'info' | 'warn' | 'error' | 'debug'): void {
const levelPrefix = level && level !== 'info' ? `[${level.toUpperCase()}] ` : '';
this.appendLine(`[${this.formatTime()}] ${levelPrefix}${message}`);
}
/**
* Log a sub-operation within a step
*/
logSubStep(message: string): void {
this.appendLine(`[${this.formatTime()}] - ${message}`);
}
/**
* Log command execution
*/
logCommand(command: string, args: string[]): void {
this.appendLine(`[${this.formatTime()}] Running: ${command} ${args.join(' ')}`);
}
/**
* Log command output
*/
logCommandOutput(output: string): void {
if (!output.trim()) return;
const lines = output.trim().split('\n');
for (const line of lines) {
this.appendLine(`[${this.formatTime()}] > ${line}`);
}
}
/**
* Finalize the log file with a summary
*/
finalize(success: boolean): void {
// End any in-progress step
if (this.currentStep) {
this.endStep(success ? 'success' : 'error');
}
const totalDuration = Date.now() - this.startTime.getTime();
const separator = '='.repeat(80);
const statusText = success ? 'COMPLETED SUCCESSFULLY' : 'FAILED';
this.appendLine('');
this.appendLine(separator);
this.appendLine(statusText);
this.appendLine(`Total Duration: ${this.formatDuration(totalDuration)}`);
this.appendLine(separator);
}
/**
* Get the relative path to the log file (for cleaner display)
*/
getRelativeLogPath(): string {
return path.relative(process.cwd(), this.logFilePath);
}
/**
* Get a clickable terminal hyperlink to the log file.
*/
getClickableLogPath(): string {
const url = `file://${this.logFilePath}`;
const displayText = this.getRelativeLogPath();
return `\x1b]8;;${url}\x1b\\${displayText}\x1b]8;;\x1b\\`;
}
}